/**
 * Settings
 */
var preDefined = new Array();
		preDefined['fullname'] = _('Firstname')+' '+_('Lastname');
		preDefined['firstname'] = _('Firstname');
		preDefined['lastname'] = _('Lastname');
		preDefined['company'] = _('Company name');
		preDefined['keyword'] = _('e.g. city');

var primary = new Array('firstname','fullname','company');
var sTriggerSource = false;
/**
 * IE functions
 */

if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/){
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++){
      if (from in this && this[from] === elt)
        return from;
    }
    return -1;
  };
}

if(typeof(trim) != 'function') {
  trim = function (str) {
    var	str = str.replace(/^\s\s*/, ''),
    ws = /\s/,
    i = str.length;
    while (ws.test(str.charAt(--i)));
    return str.slice(0, i + 1);
  }
}

// Jquery document ready
$(function() {

  // check if we need to change the visual appearance of the kgbdeals box
  if($("#register_form-country").length > 0) {
    var sVal = $("#register_form-country").val();
    sVal = trim(sVal);
    var sDomain = sVal;
    if(sVal == 'uk') {
      sDomain = 'co.uk';
    }
    if(sVal == 'us') {
      sDomain = 'com';
    }
    if(sDomain.length == 0) {
      sDomain = 'com';
    }
    $(".kgbdeals-signup a").attr('href', 'http://kgbdeals.' + sDomain);


    if(sVal == 'uk' || sVal == 'us' || sVal == 'it' || sVal == 'fr') {
      if($(".kgbdeals-signup").is(':hidden')) {
        $(".kgbdeals-signup").fadeIn('slow');
        $('#page-home #content, #page-signup #content').equalHeights();
      }
    } else {
      if(!$(".kgbdeals-signup").is(':hidden')) {
        $(".kgbdeals-signup").fadeOut('slow');
        $('#page-home #content, #page-signup #content').equalHeights();
      }
    }
  }





  //serp result actions box
  var resultActionsOpened = false;
  $('.result-actions ul').hide();
  $('.result-actions>a').click(function(){
    $('.result-actions>a').toggleClass('open');
    $('.result-actions ul').toggle();

    if(!resultActionsOpened){
      $(document).mouseup(function(e) {
        if($('.result-actions ul').css('display') == 'block'){
          if(!$(e.target).parents('.result-actions').length){
            $('.result-actions ul').hide();
            $('.result-actions>a').toggleClass('open');
          }
        }
       });
      resultActionsOpened = true;
    }
    return false;
  });


  // hide message for ie6 users
  $("a.remove-ie6-message").click(function () {
	  $("#ie6-message").fadeOut("slow");
    $.cookie('ie6_message', 'hide_ie6-message', {path: '/', expires: 200});
    return false;
  });

   //toggle popular options checkboxes selection
  $('a[rel=toggle-popular]').toggle(function() {
    $('input[type=checkbox]').removeAttr('checked');
        }, function() {
    $('input[type=checkbox]').attr('checked', 'checked');
   });

  //toggle Facebook signup info
  //$('#fb-signup-info').css('display','none');
  $('#toggle-fb-signup-info').click(function(){
    $(this).next('div').slideToggle('fast');
  });

  //toggle faq questions
  $('.faq h5').click(function(){
    $(this).next('div').slideToggle('fast');
  });

  //toggle connecting options
  $('.connect-options-toggle').click(function(){
    $(this).next('div').slideToggle('fast');
  });

  //toggle top10 persons questions
  $('.top10-overview h4 a').click(function(){
    $(this).parents('tr').next('tr').find('div').slideToggle('fast');
  });

  //toggle manual items
  $('.manual li div').hide();
  $('.manual h3').click(function(){
    $(this).next('div').slideToggle('fast');
    $(this).toggleClass('item-open');
  });

//  add hover to result box li item
//  $('div.result-closed')
//    .mouseover(function(){
//      $(this).parent('li').addClass("result-over");})
//    .mouseout(function(){
//      $(this).parent('li').removeClass("result-over");
//  });

  //css3 for non-standard browsers
  $('.tools-list li:nth-child(n+3)').css('margin-right', '0');
  $('.nav-sec dd:last-child').css('border', '0');
  $('.result-profiles table td:nth-child(2)').css('max-width', '250px');


  //tabs arrow
  $(".tabs li.current").append("<strong></strong>");

  //add class to remove margin
  $('.faq div p:last-child').addClass('p-last');

  //message boxes
  $('.message p:last-child').css({'margin' : '0'});

  // add class to last td in row
  $("table tr td:last-child").addClass("td-last");

  // table striping
  $("table.default tbody tr:nth-child(even)").addClass("alt");

  //tablerow hover for IE7
  $("table tbody tr").mouseover(function(){$(this).addClass("tr-over");}).mouseout(function(){$(this).removeClass("tr-over");});

  //tooltip
  $(".results span.info-tip").wTooltip({
    style: {
        border: "1px solid #9cb865",
        background: "#d0dfa1",
        color: "#324427",
        zIndex: "9999"
    }
  });

  $('.add-picture').click(function(){
    var position=$('#add-photo').offset();
    $('html,body').animate({scrollTop: (position.top-20)}, 500,false,function(){});
  });

  //textarea error message
  $("textarea").prev("label").children("strong").addClass("error-textarea");

	// Tim?
  $("#photo_url_btn").click (function(){
	  var url = $("#photo_url").val();
	  if ( url != '') {
		  $.post('ajax/profile_picture.php', {url: url},
			  function(data){

			  if (/^[error]/.test(data)) {
				  alert(data);
			  } else {
				  window.location.href = window.location.href;
			  }
		  	});
	  }
  });

  // Zoekinstellingen: Vinkt de checkboxen aan of uit
  $('.toggle-cat-wrap').each(function(i,n){

    checkboxCheck(n);
    $(n).next().find('li').click(function(){
			if($(this).find('input:checked').length){
				$(this).addClass('selected');
			}else{
				$(this).removeClass('selected');
			}
      checkboxCheck(n);
      checkboxPopularCheck();
    })
  });

  // Advanced search Cat check
  $('.toggle-cat-wrap > input').click(function(){
    if($(this).attr('checked')){
      $(this).parent().next().find('li').addClass('selected').find('input[type=checkbox]').attr('checked','checked');
    }else{
      $(this).parent().next().find('li').removeClass('selected').find('input[type=checkbox]').attr('checked','');
    }

    checkboxPopularCheck();
  });

  //ie6 hovers for edit profile - photos
  if(($.browser.name =='msie') && ($.browser.versionNumber == '6')){
		$('#profile-photos-list > li').mouseover(function(){
			$(this).find('div').show();
		}).mouseout(function(){
			$(this).find('div').hide();
		});
  }

  //ie6 hovers for table rows
  if(($.browser.name =='msie') && ($.browser.versionNumber == '6')){
		$('tr.result-row:hover').css({'cursor': 'pointer'}
  )};

  // Tim?
  if ($('#replace_resume').length > 0) {
	 $('#li-formfield-editprofile_form-cv_url,#li-formfield-editprofile_form-cv_file,#li-formfield-editprofile_form-cv_remove').hide();
	 $('#replace_resume').click(function(){$('#li-formfield-editprofile_form-cv_url,#li-formfield-editprofile_form-cv_file,#li-formfield-editprofile_form-cv_remove').toggle()});
  }


	// Opent alle resultaten op de serp zonder tabs
  $('#toggle-all-single').toggle(function(){
    $(this).find('span').addClass('close').html(_('Close all results'));
		var currentCategory = $('ul.results>li.has-results');
	  $(currentCategory).filter('.empty').each(function(a,b){
	  	addContentToSpider(b);
	  });

	  $(currentCategory).find('.result-closed').not('.result-empty div').removeClass('result-closed').addClass('result-open').next('div').show().find('.enc').each(function(){
    	$(this).removeClass('enc').html(decode64(this.innerHTML));
    });

  },function(){
    $(this).find('span').removeClass('close').html(_('Open all results'));
		var currentCategory = $('ul.results>li.has-results');
    $(currentCategory).find('.result-open').not('.result-empty div').removeClass('result-open').addClass('result-closed').next('div').hide();
  });

	 // disconnect external profiles
  $("a.disconnect-social-network").click(function() {
    var source = $(this).attr("id").split(":");
    $(this).after(' <img src="img/loader_tab3.gif" class="wow-verify-loader" alt="..." />');

    $.ajax({
       url: 'ajax/disconnect_profile',
       type: 'get',
       data: ( {source: source[1]} ),
       dataType: 'json',
       async: true, // needs async
       success: function(reply) {
         if( reply.status == "deleted" ) {
            $("#connect-" + source[1] + " ~ p.connect-info em").remove();
            $("#connect-" + source[1] + " ~ p.connect-info strong").after(_("Not connected"));
            $("#connect-" + source[1] + " ~ a.connect-options-toggle").remove();
            $("#connect-" + source[1] + " ~ div").hide("slow");
          }
       },
       complete:function() {
         sTriggerSource = 'invoke_ajaxstop';
        $("input[type='hidden'][value='1'][name='update'] ~ input[type='submit']").trigger('click');
       }
    });

  });

  $("a.verify-wow-site").click(function() {
    var e = $(this);
    verifyWowSite(e)
  });

  $("a.disconnect-verified-site").click(function() {
    var e = $(this);
    disconnectVerifiedSite(e);
  });

// Shrink Profile H1 that is to big
  if($('#profile-name').height() > 100){
    $('#profile-name').css('font-size','3em');

    // If it's still 2 lines, adjust the line-height to 1
    if($('#profile-name').height() > 70)
      $('#profile-name').css('line-height','1');
  }


// Shrink H1 that is too big
  if($('#h-wrap h1').height() > 50){
    $('#h-wrap h1').css('font-size','24px');
  }

  $('#settings-input input').click(function(){

  	var checked = $('#settings-input input:checked').attr('id').substr(6);
		var countrySelectors = $('.country-select select, #fill_country');
		var currentCountry = $('.country-select:visible select').val();
		countrySelectors.val(currentCountry);

//  	$('#search-bar>div').hide();
		$('#search-form-multi,#search-form-single').hide();
  	$('#search-form-'+checked).show();
  });

	// Searchsettings -> select popular sources
  $('#source-select-popular').click(function(){
		selectPopular();
  });

  // Searchsettings -> select all
  $('#source-select-all').click(function(){
		$sources = $('#search-sources');
		$sources.find('li').addClass('selected')
    $sources.find('input[type=checkbox]').attr('checked','checked');
  });

  // Searchsettings -> select none
  $('#source-select-none').click(function(){
		$sources = $('#search-sources');
		$sources.find('li').removeClass('selected');
		$sources.find('input[type=checkbox]').attr('checked','');
  });

  $('#search-settings-form').submit(function(){
		$('.error-search').remove();
  	var doReturn =  checkSearchForm($('#search-bar form:visible'));

		if(!doReturn){
			$(this).append('<strong class="error-search error-search-name">'+_('Please fill in a name')+'</strong>');
		}else if(!$('#search-sources input[type=checkbox]:checked').length){
			$(this).append('<strong class="error-search error-search-settings">'+_('Please select a source')+'</strong>');
			return false;
		}
  	return doReturn;
  });

  checkboxPopularCheck();

  $('textarea.maxlength').keypress(maxlengthCheck).keyup(maxlengthCheck).each(function(a,b){
  	maxlengthCheck(false,$(b));
  });

  $("#refer-email input[type='submit']").click(function() {
  	var fullname = $("#refer-email").find("#refer-fullname").val();
		var email = $("#refer-email").find("#refer-friend-email").val();

  	$("#refer-email").next(".message").remove();

  	if (fullname.length == 0) {
  		$("#refer-email").after('<div class="message message-error"><p>'+_("You did not enter your friend's full name")+'</p></div>');
  	} else if (email.length == 0) {
  		$("#refer-email").after('<div class="message message-error"><p>'+_("You did not enter your friend's e-mail address")+'</p></div>');
  	} else {
  		var response = makeCall('post', 'ajax/inviteForReferral.php', {email : email, fullname : fullname});
	  	if (response.substr(0,5) == 'error') {
	  		$("#refer-email").after('<div class="message message-error"><p>'+response.substr(6)+'</p></div>');
	  	} else {
	  		$("#refer-email").after('<div class="message message-go"><p>'+_('The invite has been sent')+'</p></div>');
	  		$("#refer-email").find("#refer-fullname").val('');
				$("#refer-email").find("#refer-friend-email").val('');
	  	}
  	}
  	return false;
  });

  $("#refer-share-fb, #refer-share-twitter").click(function() {
  	var msg = $(this).closest("form").find("textarea").val();
  	$("#refer-share").next(".message").remove();

  	if (msg.length > 140) {
  		$("#refer-share").after('<div class="message message-error"><p>'+_('Your message should not consist of more than 140 characters')+'</p></div>');
  		return false;
  	}

  	msg = Base64.encode(msg);
  	var source = ($(this).attr("id") == 'refer-share-fb') ? 'facebook' : 'twitter';

  	$(this).closest("form").find("input[name='msg']").val(msg);
  	$(this).closest("form").find("input[name='source']").val(source);

  	$(this).closest("form").submit();
  });

  $("#form-wowcountry input[type='submit']").hide();

	//
	$('.autosize').each(function(a,b){
		autosize($(b));
	});



  var win_form = $("#win_form").find("li.error").closest("form");
  if (win_form.length > 0 && !location.href.match(/win_form/)) {
    location.href = location.href + "#win_form";
  }


//end of document-ready
});



$("a.overlay-btn-tryagain").live('click', function() {
  $("#overlay").hide();
  $("#fullname").css('background-color', '#ffff00');
  if (!location.href.match(/page-serp/)) {
    location.href = location.href + "#page-serp";
  } else {
    location.href = location.href;
  }
  $("#fullname").val('').focus();
});

$("a.overlay-btn-quit, #overlay-tellafriend input[type='button']:eq(1)").live('click', function() {
  $.get("ajax/disable_contest.php", function(reply) { });
  $("#overlay").hide();
});

$("a#overlay-tellafriend-btn").live('click', function() {
  $(this).closest("div.overlay-btn-wrap").hide();
  $("#overlay-tellafriend").show();
});

$("input#fullname").live('keydown', function() {
  if ($(this).css('background-color') == 'rgb(255, 255, 0)') {
    $(this).css('background-color', '#fff');
  }
});

$("#overlay-tellafriend input[type='submit']").live('click', function() {
  var data = {recipient_name : $("#contest-recipientname").val(),
							recipient_email : $("#contest-recipientemail").val(),
							comments : $("#contest-comments").val()};

  $.post("ajax/mailfriend_contest.php", data, function(response){
    if(response == 'success'){
      $("#overlay-tellafriend").find('#mail-friend-error').html('').hide();
			$("#overlay-tellafriend").find('#mail-friend-msg').html('De e-mail is succesvol verzonden').show();
			$("#overlay-tellafriend").find("input[type='text']").val('');
		} else{
		  $("#overlay-tellafriend").find('#mail-friend-msg').html('').hide();
	  						//$(resultblock).find('#mail-friend-error').html(response).show();
	  	$("#overlay-tellafriend").find('#mail-friend-error').html(response.substr(7)).show();
  	}
	});
  return false;
});


/**
 * Alters the font-size to make the text fit
 */
autosize = function(elm){
	var currentHeight
	var currentLineHeight   = parseInt(elm.css('line-height'));
	var newFontSize					= parseInt(elm.css('font-size'));
	var run									= Math.round(newFontSize/2);

	do{
		currentHeight = parseInt(elm.css('height'));
		if(currentHeight > (currentLineHeight*1.1)){
			elm.css('font-size',--newFontSize);
			run--;
		}else{
			run=0;
		}
	}while(run);
};

$("a.iframe-loading").live('click', function() {
	var element = $(this);
	$(function() {
		$(element).fancybox({frameWidth: 800, frameHeight: 480});
		$(element).click();
		$(element).removeClass('iframe-loading');
		$(element).addClass('iframe');
	});
	return false;
});

//facebook login loading message
$("a.iframe-loading-fb").live('click', function() {
	var element = $(this);
	$(function() {
		$(element).fancybox({'frameWidth': 500, 'frameHeight': 150, 'showCloseButton': false, 'hideOnOverlayClick': false});
		$(element).click();
		$(element).removeClass('iframe-loading-fb');
		$(element).addClass('iframe');
	});
	return false;
});

maxlengthCheck = function(e,elm){
	if(e)
		var elm = $(this);

	var elmClass = elm.attr('class');
	var maxlength = elmClass.match(/maxlength-[0-9]+/gi);
	var stringMaxLength = parseInt(maxlength[0].substr(10));
	var charCounter = elm.siblings('.char-counter');
	var charCount = stringMaxLength-elm.val().replace(/\n/g,"\n\r").length;
	var msg = ngettext('%1 character remaining','%1 characters remaining',charCount);

  var classNames = 'char-counter';
	if(charCount < 0){
    classNames += ' char-counter-error';
  	msg = ngettext('%1 character too long','%1 characters too long',(0-charCount));
	}else if(charCount < 20){
    classNames += ' char-counter-warning';
	}
  charCounter.html(msg).attr('class',classNames);

}

/**
 * When a search form is submitted, every input in that form will be checked.
 * returns false back to the form when the form was NOT filled in right
 * returns true back to the form when the form was filled in right
 */
$.elementReady('content',function(){
  $('.search').submit(function(){
  	$('.error-search').remove();
  	var doReturn = checkSearchForm($(this));
  	if(doReturn && $('#search-settings-form').length){
			if(!$('#search-sources input[type=checkbox]:checked').length){
				$(this).append('<strong class="error-search error-search-settings">'+_('Please select a source')+'</strong>');
			}else{
				$('#search-settings-form').submit();
			}
	    return false;
	  }
		if(!doReturn){
			$(this).append('<strong class="error-search error-search-name">'+_('Please fill in a name')+'</strong>');
		}
	  return doReturn;
  });

  $('.search input[type="text"]').focus(function(){

  	// Removes the error message, that is in place when no name was given, if the focus is done on the firstname or on the fullname input
		if(this.id == 'firstname' || this.id == 'fullname')
			$('.error-search-name').remove();

    if(!testInput($(this)) && !$(this).hasClass('firsttime'))
      $(this).val('').removeClass('predefined firsttime');

  }).keydown(function(){
    if(!testInput($(this)))
      $(this).val('').removeClass('predefined firsttime');

  }).blur(function(){
    if(!$.trim($(this).val()) || !testInput($(this)))
      $(this).addClass('predefined').val(preDefined[$(this).attr('id')]);
  }).click(function(){
  	if(!testInput($(this)))
  	  $(this).val('').removeClass('predefined firsttime');
  });
});

function checkSearchForm(f){
  var formElements = f.find('input[type="text"]');
  $('#search-settings-form #search-submit input').val('');

  var doReturn = false;
  formElements.each(function(a,b){

    var c = $(b);
    var v = c.val();
        v = $.trim(v);
    var i = c.attr('id');

    if(primary.indexOf(i) != -1){
      if(v != preDefined[i] && v){
				c.val(v);
        doReturn = true;
			}else
        return false;
    }else{
      if(doReturn && (v == preDefined[i])){
        c.val('');
        v = '';
      }
    }
    $('#search-settings-form #fill_'+i).val(v);
  });

  if($('.country-select:visible select').length){
 		var countrySelectors = $('.country-select select, #fill_country');
 		var currentCountry = $('.country-select:visible select').val();

  	if(doReturn && !currentCountry){
//			countrySelectors.attr('disabled',true).val(currentCountry);
			countrySelectors.val(currentCountry);
	  }else{
//	  	countrySelectors.attr('disabled',false).val(currentCountry);
	  	countrySelectors.val(currentCountry);
	  }
  }

  return doReturn;
}


/**
 * Checks if the provided input has the predefined value.
 * false: if equals to predefined
 * true:  if not equal to predefined
 */
function testInput(b){
	return ($.trim(b.val()) != preDefined[b.attr('id')]);
}


function verifyWowSite(e) {

  var url = $(e).prev("input").val();
  var msg_start ='<div class="message message-error"><p>';
  var msg;
  var msg_end   = '</p></div>'

  if( url.length > 0 ) {
   if($('img.wow-verify-loader').length > 0) {
    $('img.wow-verify-loader').remove();
   }
   if($(e).next('div.message').length > 0) {
    $(e).next('div.message').remove();
   }
   $(e).parents("div.box").append(' <img src="img/loader_tab3.gif" class="wow-verify-loader" alt="..." />');

   var encodedUrl = encodeURIComponent( url );
   $.get("ajax/verify_site.php?url=" + encodedUrl, function(reply) {
    if( reply.http_code == 200 && !reply.error_msg)  {
      var div =  $(e).parent("div");
      $(div).html( reply.response_html );
      // re-bind functions
      $(div).find('.connect-options-toggle').click(function(){
        $(this).next('div').slideToggle('fast');
       });
      // another rebind
      $(div).find("a.disconnect-verified-site").click(function() {
        var e = $(this);
        disconnectVerifiedSite(e);
      });
    } else if (reply.http_code > 0 && reply.http_code != 200) {
      msg = _("Error")+" "+ reply.http_code+": "+_("The verification file could not be found.");
      $(e).next('div').remove();
      $(e).after(msg_start + msg + msg_end);
      $(e).next('div.message').show();
    } else if ( reply.error_msg ) {
      $(e).next('div').remove();
      $(e).after(msg_start + reply.error_msg + msg_end);
      $(e).next('div.message').show();
    }
    $('img.wow-verify-loader').remove();
    sTriggerSource = 'invoke_ajaxstop';
    $("input[type='hidden'][value='1'][name='update'] ~ input[type='submit']").trigger('click');
   }, "json");

  }

}

function disconnectVerifiedSite(e) {
    var id = $(e).attr("id");
    var idSplitted = id.split(":");
    var siteIndex = $(e).parents("div.box").attr("id");
    var siteIndexSpl = siteIndex.split(":");

    $(e).after(' <img src="img/loader_tab3.gif" class="wow-verify-loader" alt="..." />');
    $.get("ajax/remove_verified_site.php?id=" + idSplitted[1] + "&siteindex=" + siteIndexSpl[1], function(reply) {
      if( reply.status == "deleted" ) {

       var divbox = $(e).parents("div.box");
       $(divbox).html(reply.response_html);
       $(divbox).find("a.verify-wow-site").click(function() {
          var e = $(this);
          verifyWowSite(e)
        });
      }
    }, "json");
    sTriggerSource = 'invoke_ajaxstop';
  $("input[type='hidden'][value='1'][name='update'] ~ input[type='submit']").trigger('click');
}



// Controleerd voor de geselecteerde categorie of alle onderliggende checkboxes aangevinkt zijn, zo ja moet de checkbox naast de categorie naam ook aangevinkt zijn
checkboxCheck = function(n){
	var $next = $(n).next();
	$next.find('li').removeClass('selected').find('input:checked').parent().addClass('selected');
	if($next.find('input').length == $(n).next().find('input:checked').length)
		$(n).find('input[type=checkbox]').attr('checked','checked');
	else
		$(n).find('input[type=checkbox]').attr('checked','');


}

/**
 * Checks all checkboxes and if necessary changes the radiobutton
 */
var allCheckboxes,numAllCheckboxes;
  checkboxPopularCheck = function(){
	$('.error-search-settings').remove();
  if(!allCheckboxes){
    allCheckboxes = $('#search-sources').find('li input[type=checkbox]');
    numAllCheckboxes = allCheckboxes.length;
  }

  var numChecked = $('#search-sources').find('li input[type=checkbox]:checked').length;

  if(numChecked == numAllCheckboxes){
    $('#source-select-all').attr('checked','checked');
  }else if(!numChecked){
    $('#source-select-none').attr('checked','checked');
  }else{
    var populars = true;
    allCheckboxes.each(function(a,b){
      if(!($(b).hasClass('popular') && $(b).attr('checked')) && !(!$(b).hasClass('popular') && !$(b).attr('checked'))){
        populars = false;
      }
    });
    if(populars)
      $('#source-select-popular').attr('checked','checked');
    else
      $('#search-sources-toggle input').attr('checked','');
 }
}

// Gooit een trigger op een algemene onclick
document.onclick=trigger

function trigger(e){
  var trgt,trType;

  if (!e)
    var e = window.event;

  // Firefox etc.
  if (e.target){
    var trgt	= e.target;
    var trType	= trgt.nodeName.toLowerCase();
  }else if (e.srcElement){
    var trgt	= e.srcElement;
    var trType	= trgt.tagName.toLowerCase();
  }

  // Opent de result-info voor spiders die opgebouwd zijn doormiddel van tabellen.
  if($(trgt).is('table tr.result-row, table tr.result-row *') && trType != 'a'){
  	// hier nog een clicktale exec
    $(trgt).parents('tr').toggleClass("result-info-open").next().toggleClass("result-row-info-closed").toggleClass("result-row-info-open");
  }

  // Opening the result-content of a spider
  if($(trgt).is('.results li > div:first-child *,.results li > div:first-child')){

		var clickedDiv = $(trgt).find('h3').text();

		if(typeof(ClickTaleExec)=='function') {
			ClickTaleExec("jQuery('h3:contains(\""+clickedDiv+"\")').parent('div').click();");
		}

    var currentLi = $(trgt).parents('li');

    if($(currentLi).hasClass('result-ad') || $(currentLi).hasClass('result-empty'))
      return;


    if($(currentLi).hasClass('empty'))
      addContentToSpider(currentLi);

		$(currentLi).find('.enc').each(function(){
    	$(this).removeClass('enc').html(decode64(this.innerHTML));
    });

      $(currentLi).find('div.result-content').toggle();
    $(currentLi).find('> div:first-child').toggleClass("result-closed").toggleClass("result-open");
    return;
  }

	// Opent een subresultataat in een spider die geen tabel heeft
  if($(trgt).hasClass('result-title')){
    $(trgt).toggleClass("result-info-open").next(".result-info").toggle();
  }
	// Opent een subresultataat in een spider die geen tabel heeft (nodig als je op bijvoorbeeld de ballon klikt
  if($(trgt).parent().hasClass('result-title')){
    $(trgt).parent().toggleClass("result-info-open").next(".result-info").toggle();
  }

  switch(trType){
    case 'img':
    	// open image popup
      if($(trgt).parent().hasClass('img-info-link')){
      	$('li.img').css({'z-index' : '0'}).find('.result-info').hide();
      	var imageBlock = $(trgt).parents('li.img');
      	$(imageBlock).css({'z-index' : '98'}).find('.result-info').css({'z-index' : '99'}).show();
      	return false;
      }

      // User clicks on a link with a "rel=external"
      if(trgt.parentNode.getAttribute('rel')){
	      if(trgt.parentNode.getAttribute('rel').search('external') != -1){
  	    	trgt.parentNode.setAttribute('target','_blank');

						var clickid = $(trgt).parents('.result-content').parent().attr('id').substr(7);
						var clickhref = $(trgt).parent().attr('href');

						$.get('ajax/clickout.php',{'url' : clickhref,'id':clickid});
	      }
      }
    break;

    case 'a':

    	if($(trgt).hasClass('search-different')){
        $('#add-link-predefined-search,.message').hide();
        $('#add-link-predefined form').show();
      	return false;
      }
    	// Opening the tag box
			if($(trgt).hasClass('tag-link') && !$(trgt).hasClass('tag-side')){
        $('li.tag').css({'z-index' : '0'}).find('.result-info').hide();
      	var imageBlock = $(trgt).parents('li.tag');
      	$(imageBlock).css({'z-index' : '9998'}).find('.result-info').css({'z-index' : '9999'}).show();
      	return false;
			}

      // User wants to edit is comment
      if($(trgt).parent().hasClass('edit-comment') || $(trgt).parent().hasClass('add-comment')){
        var resultBlock = $(trgt).parents('.result-info');
        $(resultBlock).find('.add-link-from-results').toggle();
        $(resultBlock).find('.add-link-from-results form').submit(function(){
          var queryString = 'action=edit&'+$(this).serialize();

          $.post('ajax/add_profile_link.php',queryString,function(response){
            $(resultBlock).find('.add-comment,.add-link-from-results').hide();
            $(resultBlock).find('.edit-comment,.delete-comment,.link-comments').show();
            $(resultBlock).find('.link-comments p').html(response.msg);
          },'json');
          return false;
        });
      }

      // User wants to delete the comment
      if($(trgt).parent().hasClass('delete-comment')){
        if(confirm(_('Are you sure you want to delete this comment?'))){
          var resultBlock = $(trgt).parents('.result-info');
          $(resultBlock).find('textarea[name="comment"]').val('');
          var queryString = 'action=edit&'+$(resultBlock).find('form').serialize();
          $.post('ajax/add_profile_link.php',queryString,function(response){
            $(resultBlock).find('.edit-comment,.delete-comment,.add-link-from-results,.link-comments').hide();
            $(resultBlock).find('.add-comment').show();
            $(resultBlock).find('.link-comments p').html('');
          },'json');
        }
      }

      // User wants to delete the saved link
      if($(trgt).parent().hasClass('delete-link')){
        if(confirm(_('Are you sure you want to delete this link?'))){
          var resultBlock = $(trgt).parents('.result-info');
          $(resultBlock).find('textarea[name="comment"]').val('');
          var queryString = 'action=delete&'+$(resultBlock).find('form').serialize();
          $.post('ajax/add_profile_link.php',queryString,function(response){
            if ( response.type == 'link_del' ) {
              $(resultBlock).fadeOut();
              window.location.href = window.location.href;
            }
          },'json');
        }
      }


    	if($(trgt).hasClass('tag-close-info')){
				$(trgt).parents('li.img,li.tag').css({'z-index' : '0'}).find('.result-info').hide();
    		return false;
    	}

    	// User clicks on "add link" link
      if(trgt.parentNode.className == 'add-to-profile'){
        var resultblock = $(trgt).parents('.result-info');

        if($(resultblock).find('.add-link-from-results h4').length){
          $('.add-link-from-results').html('');
          $('#add-link-error').hide();
        }else{
      	  $('#add-link-error').hide();

      	  $('.mail-result-to-friend').html('');
          $('#mail-friend-error').hide();
          $('#mail-friend-msg').hide();

				  $('.add-link-from-results').html('');
			  	$(resultblock).find('.add-link-from-results').html($('#add-link-from-results').html());

		  		var url = $(trgt).attr('rel');

	  			$('.add-link-from-results form').submit(function(){
  					$.post(url,{'comment' : $(this).find('textarea').val()}, function(response){
					  	if(response == 'success'){
				  			$(resultblock).find('.add-link-from-results').html(_('Result is saved'));
			  				$(resultblock).find('.add-to-profile').html(_('Result is saved')).removeClass('add-to-profile').addClass('saved-to-profile');
			  				if($('body#page-profile').length)
			  				window.location.href = window.location.href;
					  	}else{
	  						$(resultblock).find('#add-link-error').html(response).show();
  						}
					  	return false;
				  	});
			  		return false;
		  		});
        }
        return false;
      }

      // User clicks on "send result to friend" link
      if(trgt.parentNode.className == 'action-mail'){
        var resultblock = $(trgt).parents('.result-info');

        if($(resultblock).find('.mail-result-to-friend h4').length){
          $('.mail-result-to-friend').html('');
          $('#mail-friend-error').hide();
          $('#mail-friend-msg').hide();
        }else{
      	  $('#mail-friend-error').hide();
					$('#mail-friend-msg').hide();

					$('.add-link-from-results').html('');
          $('#add-link-error').hide();

				  $('.mail-result-to-friend').html('');
			  	$(resultblock).find('.mail-result-to-friend').html($('#mail-result-to-friend').html());

		  		var url = $(trgt).attr('rel');

	  			$('.mail-result-to-friend form').submit(function(){
	  				var data = {searchedname : resultblock.find("input[name='searchedname']").val(),
	  										sender_name : resultblock.find("#mail-result-sendername").val(),
												sender_email : resultblock.find("#mail-result-senderemail").val(),
												recipient_name : resultblock.find("#mail-result-recipientname").val(),
												recipient_email : resultblock.find("#mail-result-recipientemail").val(),
												comments : resultblock.find("#mail-result-comments").val()};

  					$.post(url, data, function(response){
					  	if(response == 'success'){
					  		$(resultblock).find('#mail-friend-error').html('').hide();
					  		$(resultblock).find('#mail-friend-msg').html(_('This result has been sent successfully')).show();
					  		$('.mail-result-to-friend form').find("input[type='text'], textarea").val('');
				  		} else{
					  		$(resultblock).find('#mail-friend-msg').html('').hide();
	  						$(resultblock).find('#mail-friend-error').html(response).show();
	  						$(resultblock).find('#mail-friend-error').html(response.substr(7)).show();
  						}
					  	return false;
				  	});
			  		return false;
		  		});
        }
        return false;
      }

      // User clicks on a link with a "rel=external"
      if(trgt.getAttribute('rel')){
	      if(trgt.getAttribute('rel').search('external') != -1){
  	    	trgt.setAttribute('target','_blank');

            var clickid = $(trgt).parents('.result-content').parent().attr('id').substr(7);
            var clickhref = $(trgt).attr('href');
            var clickcontent = $(trgt).parents('.result-info').find('.add-to-profile>a').attr('href');


						if(typeof(searchID) != 'undefined') {
							$.post('ajax/clickout.php',{'url' : clickhref,'id':clickid, 'searchID':searchID, 'content':clickcontent});
						} else {
							$.post('ajax/clickout.php',{'url' : clickhref,'id':clickid, 'content':clickcontent});
						}
	      }
      }

   // hide message-new op homepage including cookie
      if($(trgt).hasClass('remove-message')){
      	var messageBar = $(trgt).parent();
  		var messageBarId = messageBar.attr('id');
  		messageBar.fadeOut("slow");
	    $.cookie(messageBarId, 'hide_'+messageBarId, {path: '/', expires: 200});
	    return false;
      }

      if($(trgt).hasClass('box-next')){

      	var boxxed = $(trgt).parents('.boxed');
      	var current = $(boxxed).find('.current-box');

      	if($(current).next('.is-box').length){
	      	$(boxxed).find('.is-box').hide();
	      	$(current).removeClass('current-box').next('.is-box').show().addClass('current-box');
	      	if(!$(current).next('.is-box').next('.is-box').length)
	      		$(boxxed).find('.box-next').addClass('disabled');
	      	$(boxxed).find('.box-prev').removeClass('disabled');
      	}
      	return false;
      }

      if($(trgt).hasClass('box-prev')){
				var boxxed = $(trgt).parents('.boxed');
      	var current = $(boxxed).find('.current-box');

      	if($(current).prev('.is-box').length){
	      	$(boxxed).find('.is-box').hide();
	      	$(current).removeClass('current-box').prev('.is-box').show().addClass('current-box');
	      	if(!$(current).prev('.is-box').prev('.is-box').length)
	      		$(boxxed).find('.box-prev').addClass('disabled');
      		$(boxxed).find('.box-next').removeClass('disabled');
      	}
      	return false;
      }
    break;
  }
}
function initResult(id){
//	time.start('initResult '+id);
	// add class to last td in row
  $(id+" table tr td:last-child").addClass("td-last");

  //align right for table toggle buttons
  $(id+' table td:last-child').not('td:first-child').attr({
    align: "right"
  });
//  time.stop('initResult '+id);
}

function clickToLogin(e){
  $('html,body').animate({scrollTop: 0}, 500,false,function(){
    $('#loginbox').slideDown('fast', function(){
      $('#useremail').focus();
    });
  });

}


$.elementReady('photo_upload',function(){
	new AjaxUpload('#photo_upload', {
        action: 'ajax/profile_picture.php',
		onSubmit : function(file , ext){
			if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
				// extension is not allowed
				alert('Error: only images allowed');
				// cancel upload
				return false;
			}
		},
		onComplete: function(file, response) {
			//$('#avatar-upload').attr('src',response);
			if (/^[error]/.test(response)) {
				 alert(response);
			} else {
				window.location.href = window.location.href;
			}
            //$("<img/>").attr("src", response).attr("width",'150').appendTo("#profile-photos-list");
			//$('.jcrop-holder img').attr('src',response);
			//$('.jcrop-holder').remove();
			//$('#avatar-upload').css('display','block');
			//$('#avatar-upload').Jcrop();

		}
	});
});

function deletePhoto(name) {
	if(confirm(_('Are you sure you want to delete this photo?'))){
		$.get('ajax/profile_picture.php', {'delete' : name},
				function(data) {
					if (data == 'avatar' || data == 'photo') {
						window.location.href = window.location.href;
					} else {
						$("#photo_" + data).fadeOut("slow");
					}
		});
	}
}


function checkDomain(p_sDomain, p_sUrl, o_El) {

  if($(o_El).parent().find('a.domain-buy-yes, span.domain-buy-no').length == 0) {
    var base    = $("base").attr('href');
    var sDomain = encodeURIComponent(p_sDomain);
    var sUrl    = encodeURIComponent(p_sUrl);
    $.ajax({
      url: base + 'ajax/checkDomain.php',
      cache: false,
      data: ({domain: sDomain, url: sUrl}),
      dataType: 'json',
      timeout: 30000,
      error: function(xhr, textStatus, errorThrown) {
        $(o_El).after('<span class="domain-buy-no">' +  _('not available')  + '</span>');
        checkDomainLoaded();
        disableCacheId(p_sDomain);
      },
      success: function(reply, textStatus, xhr) {
        $(o_El).after(reply.html);
        checkDomainLoaded();
      }
    });
  } else {
    checkDomainLoaded();
  }
}

function disableCacheId(p_sDomain) {
  var base    = $("base").attr('href');
   $.ajax({
      url: base + 'ajax/disableCacheId.php?domain=' + p_sDomain,
      cache: false,
      timeout: 1000
    });
}

var sPrevHref = '';
function checkDomainLoaded() {
  var bLoaded = true;
  $("#box-domain li").each( function() {
    if($(this).find('a.domain-buy-yes, span.domain-buy-no').length == 0) {
      bLoaded = false;
    }
  });

  if(bLoaded == true ) {
    $("#box-domain h3").removeClass('loading').addClass('done');

    // track analytics
    $("#box-domain li a").live('click',function() {

        var sHref = $(this).attr('href');


        if(sPrevHref != sHref) {
          sPrevHref = sHref;
          if(sHref.indexOf('godaddy') != -1) {
              if(typeof(_gaq) != 'undefined') {
                _gaq.push(['_trackPageview','/out/godaddy']);
              }
              $.get("ajax/clickout.php?type=ad&site=godaddy&url=" + encodeURIComponent(sHref));
          } else {
              if(typeof(_gaq) != 'undefined') {
                _gaq.push(['_trackPageview', '/out/transip']);
              }
              $.get("ajax/clickout.php?type=ad&site=transip&url=" + encodeURIComponent(sHref));
          }
        }
    });
  }
}

$.elementReady('box-domain', function() {
  var base = $('base').attr('href');
  var sArg1, sArg2;
  sArg1 = $("input[name='domain-arg1']").val();
  sArg2 = $("input[name='domain-arg2']").val();


  $.ajax({
    url: base + 'ajax/getDomainBox.php',
    cache: false,
    data: ({arg1: sArg1, arg2: sArg2}),
    dataType: 'json',
    async: true,
    success: function(reply) {
      $("#box-domain").html(reply.html);
    }
  });

});


function startCheckDomains() {
    $('#box-domain').find('h3').addClass('loading');
  	$('#box-domain').find("li a").each(function() {
  	   checkDomain($(this).text(), $(this).attr('href'), $(this));
  	});
}

//$.elementReady('filters', function() {
//    $(this).find('h3').addClass('loading');
//});


$.elementReady('found-places', function(){
	$('.toggle-places').click(function(){
		$('#result-places li').removeClass('hide');
	    $(this).hide();
	});
});

$.elementReady('found-keywords', function(){
	$('.toggle-keywords').click(function(){
		$('#result-keywords li').removeClass('hide');
  	  $(this).hide();
	});
});


$.elementReady('filters', function() {

  $.get("ajax/loadTags.php?type=box", function(reply) {
    $("#filters").html(reply);

		$filterKeyword = $('#filters-keyword');
	  if($filterKeyword.length){
		 $("#filter-keyword").val($filterKeyword.html());
	  }
  });



	$(function(){
	  loadKeywords();
	});
});

function tagsLoaded() {
  $.get("ajax/loadTags.php?type=spidercontents", function(reply) {
    $("#result-tags .result-content").html(reply);
  });
}

function loadKeywords(){
	$.get("ajax/loadTags.php?type=contents", function(reply) {
    $("body").append(reply);
  });
}

function paginate(id){
  switchToTab(id);
  $('html,body').animate({scrollTop: (0)}, 0,false,function(){});
}

function TabClick(id) {
	var tabId = $(id).parent("li").attr("id");

	if(typeof(ClickTaleExec) == 'function' ) {
    ClickTaleExec('switchToTab("'+tabId+'");');
  }
  switchToTab(tabId);
}

function scroller(location){var position=$(location).offset();
  $('html,body').animate({scrollTop: (position.top-20)}, 500,false,function(){});
}

/**
 * Login box and language box
 */
  $('.dropbox').live('click',function(){

//$(function(){
//	  $('.dropbox').click(function(){
  	var clickedBox = $(this).attr('id').substr(8);
//		document.title=clickedBox;
  	if(clickedBox.length) {
  	 var clicked = $('#'+clickedBox);
  	} else {
  	  return false;
  	}

		if(clicked.is(':visible')){
      clicked.hide();
		}else{
			clicked.slideToggle('fast',function(){
				if(clickedBox == 'loginbox' && clicked.is(':visible')){
					 $('#useremail').focus();
				}
			});
		}

//  	if(clicked.hasClass('opened')){
//  		clicked.removeClass('opened');
////			document.title='ds2';
////			$('#dropbox-loginbox').focus();
//  	}else{

			if(clicked.is(':visible')){
				$(document).mouseup(function(e) {

  			if($(e.target).attr('id') != clickedBox && (!$(e.target).parents('#'+clickedBox).length) && ($(e.target).attr('id') != 'dropbox-'+clickedBox) && ($(e.target).parent().attr('id') != 'dropbox-'+clickedBox) && (clickedBox != $(e.target).attr('id'))){

					clicked.hide();
  			}
  		});
  		clicked.addClass('opened');
  	}

    if(clickedBox == 'loginbox') {
        return false;
    }
  });
//});
	//check to see if parent of toggleboxes are ready

// kgbpeople
$.elementReady('masthead', function(){
  initLoginForm();
});

// wieowie
$.elementReady('top-bar', function() {
  initLoginForm();
});


function initLoginForm() {

  $('#loginform').submit(function(){
	  var form = this;
    $.post("ajax/login.php", {email: $("input[name=email]", form).val() , password: $("input[name=password]", form).val()},function(data){
      if (data.error) {
        if($(form).find('span#login-error').length == 0) {
          $(form).prepend('<span id="login-error" class="error" style="display: none;">' + _("Email and/or password incorrect") + '</span>');
        }
        $('span.error', form).fadeOut(300).fadeIn(500);	// Hide: Remind user that the login was incorrectly
      }else{
        if($('#page-serp').length){
          $('#login-ini,.isNotLoggedIn,#add-link-from-results h4 span,.add-link-from-results h4 span').hide();
          $('#logged-in').show();
          $('#loginbox').slideUp('fast');
          $('#logged-in .username').html(data.first_name + ' ' + data.last_name);
          if($('#myprofile').length > 0) {
            $('#myprofile').attr('href','./'+data.profile_url).html(data.profile_name);
          } else {
            $('#logged-in a.username').attr('href','./'+data.profile_url);
          }
          if(data.is_pro){
            $('#add-link-from-results,.add-link-from-results,.add-to-profile').hide();
            $('#logged-in .username').append('<span>pro</span>')
          }else{
            $('#add-link-from-results form,.add-link-from-results form').show();
          }
        } else{
          	window.location.href = window.location.href;
        }
//        }else if($('#page-alerts').length || $('#loginform2').length){
//        	window.location.href = window.location.href;
//        } else{
//          window.location.href = './'+data.profile_url;
//        }
      }
    },'json');
    return false;
  });
}

//var searchtypetab;
//var serp;

/**
 * Switches the selected tab to the given tab
 */
var currentTab,serpHidesNoResults;
var $adSenseBlocks;
function switchToTab(tabId){

	if(!currentTab)
		currentTab = $('div#searchtypetab>ul>li.current').attr('id');

//	moveAdsense(tabId);

	$('#'+currentTab).removeClass('current');
	$('#'+tabId).addClass('current');

	$('div#results-'+currentTab).hide();
	$('div#results-'+tabId).show();

	if(currentTab == 'wowprofile' && tabId != 'wowprofile'){
		$('#side-col').show();
	}else if(currentTab != 'wowprofile' && tabId == 'wowprofile'){
		$('#side-col').hide();
	}


	currentTab =  tabId;
}

function moveAdsense(tabId){
	if($.browser.opera){
		return false;
	}

	var minBlocks = 4;
	if(!$adSenseBlocks){
		$adSenseBlocks = $('.result-google-ad');

		if($('.empty-results').length){
			serpHidesNoResults = true;
		}
	}

	// .has-results dynamisch maken aan de hand van "geen resultaten box".
	if(serpHidesNoResults){
		var $resultBlocks = $('#results-'+tabId+' ul.results>li.has-results').not('#result-wanted,#result-profiles,#result-pfproperty,#result-pfpeople,.result-google-ad');
	}else{
		var $resultBlocks = $('#results-'+tabId+' ul.results>li').not('#result-wanted,#result-profiles,.result-google-ad');
	}

	// First Adsense Block
	$resultBlocks.first().before($adSenseBlocks[0]);

	// Last Adsense Block
	$resultBlocks.last().after($adSenseBlocks[2]);

	var numberOfBlocks = $resultBlocks.length;
	if(numberOfBlocks >= minBlocks){
		var middleAfterBlock = Math.floor(numberOfBlocks/2);
		$resultBlocks.eq(middleAfterBlock).before($adSenseBlocks[1]);
	}

	$adSenseBlocks.show();
}

// ---

// Flickr and faces images: display comment form
$.elementReady('images-images',function(){
	$('#result-images a.verified-add').click(openImageVerifiedAdd);
	$('#result-images a.close-img-addform').click(closeImageVerifiedAdd);
});

$.elementReady('images-flickr',function(){
	$('#result-flickr a.verified-add').click(openImageVerifiedAdd);
	$('#result-flickr a.close-img-addform').click(closeImageVerifiedAdd);
});
function openImageVerifiedAdd(){
	$('.add-img').css({'display' : 'none'}).parent('li').css({'z-index' : '0'});

	var url = $(this).attr('href');
	var obj = $(this);
	$(this).next('div').attr('id','verified-image-form').css({'z-index' : '9999'}).toggle().find('form').submit(function(){
		$.post(url,{'comment' : $(this).find('textarea').val()}, function(d){
			if(d == 'success'){
				$('#verified-image-form form').html(_('Result is saved'));
				setTimeout(function() {
					$('#verified-image-form').attr('id','').hide(2000);
				},1000);
			}else{
				alert(d);
			}
		});
		return false;
	});
	$(this).parent('li').css({'z-index' : '9998'});
	return false;
}

function closeImageVerifiedAdd(){
	$(this).parent('div').hide();
	$(this).parent('div').parent('li').css({'z-index' : '0'});
	return false;
}

$.elementReady('profile-sites',function(){
	initResult('.profile-link-li');
	//$(this).dragsort({ dragSelector: ".profile-link-li" });
});

$('#filter-keyword').live('focus',function(){
	if($(this).val() == _('enter keyword')){
	  $(this).removeClass('predefined').val('');
	}
}).live('blur',function(){
  if($(this).val() == ''){
	  $(this).addClass('predefined').val(_('enter keyword'));
	}
});

$('#filters form').live('submit',function(){
  $filterKeyword = $('#filter-keyword');
  if($filterKeyword.val() == _('enter keyword')){
    $filterKeyword.val('');
  }

	$(this).attr('action',window.location.href);
});
/************* other functions ****************/

function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;

	do {curDate = new Date();}
	while(curDate-date < millis);
}

function checkDate(field) {
	var val = field.value;
	if (val.length == 2 || val.length == 5) {
		field.value = field.value + '-';
	}
	val = field.value.replace(/-/g,'');
	if (val.length == 8) {
		var date = new Date(val.substr(4,4),val.substr(2,2)-1,val.substr(0,2));
		$(field).datepicker( 'setDate', date );
	} else {
		return;
	}
}
function updateSelectField(field,target,script) {
	var value = field.options[field.selectedIndex].value;
	$.getJSON(script,{id: value}, function(j){
        	var options = '';
            for (var i = 0; i < j.length; i++) {
                options += '<option value="' + j[i].value + '">' + j[i].label + '</option>';
            }
            $(target).html(options);
    });
}

function copyNumFoundToResults(id,value){
  var newValue = ngettext('%1 result found','%1 results found',value);
  $('li#result-'+id).removeClass('result-loading').addClass('has-results').find('.result-closed>span').html(newValue);
  if (typeof('java_spider') != undefined && java_spider) {
	  $('li#result-'+id+'>div>h3,li#result-'+id+'>div>span').css('color','red');
	  java_spider = false;
  }
}

function copyFoundToResults(id){
  if(id == 'keywords') {
    $("#filters").find("h3").removeClass("loading").addClass("done");
  }
	var divname='result-'+id;
	var newdiv='found-'+id;document.getElementById(divname).innerHTML=document.getElementById(newdiv).innerHTML;
}

function removeAddVerified(){
	$('#add-verfified').remove();
}

var noEmptyResults = true;
var addExtraToEmptyResults = '';
function hideEmptyResult(id,name){

	if(noEmptyResults){
		// Quickfix: .empty-results doesn't exists here

		if($('.empty-results').length){
			$('.empty-results').show().find('ul').html(addExtraToEmptyResults);
			noEmptyResults = false;
		}
	}

	if (typeof(java_spider) != "undefined" && java_spider) {
		var li_start = '<li style="color:red">';
	} else {
		var li_start = '<li>';
	}

	noResultsFound(id);

	var obj = $('#result-'+id);
	if(obj.is(':visible')){
    obj.fadeOut('slow');
	}else{
    obj.hide();
	}



	if(noEmptyResults){
		addExtraToEmptyResults += li_start+name+'</li>';
	}else{
		$('.empty-results ul').append(li_start+name+'</li>');
	}
}

function noResultsFound(id){
  switch(id){
		case 'places':
		case 'keywords':
			$('#result-'+id+' p').attr('class','result-empty').html(_('no results found'));
			$("#filters").find("h3").removeClass("loading").addClass("done");

		break;
		default:
			$('#result-'+id).attr('class','result-empty').find('div>span').html(_('no results found'));
		break;
	}
	$('#result-'+id).attr('class','result-empty').find('div>p.result-loading').html(_('no results found'));
	if (typeof(java_spider) != "undefined" && java_spider) {
		  $('li#result-'+id+' h3').css('color','red');
		  java_spider = false;
	  }
}

function addContentToSpider(elm){
	var currentId = $(elm).attr('id').substr(7);

  if($(elm).hasClass('empty')){
    document.getElementById('result-'+currentId).innerHTML = document.getElementById('found-'+currentId).innerHTML;
    $(elm).removeClass('empty');
  }
}


function serp_catagoryisready(id){
  // Category is ready, add a check beside the name

	if(id.length > 0) {
		$('#'+id+'>a>span.tab-loading').attr('class','tab-done');
	}

	if(id != 'wowprofile')
		var currentCategory = $('div#results-'+id+'>ul.results>li.has-results');

	// Toggle result open and close
  $('div#results-'+id+' a.toggle-all-results').toggle(function(){



  	$('.main-col:visible a.toggle-all-results span').addClass('close').html(_('Close all results'));
//    $(this).find('span').addClass('close').html(_('Close all results'));

//    if($('.main-col:visible').length > 1){


	    $('.main-col:visible li.has-results').filter('.empty').each(function(a,b){
	  	  addContentToSpider(b);
	    });
	    $('.main-col:visible li.has-results').find('.result-closed').not('.result-empty div').removeClass('result-closed').addClass('result-open').next('div').show().find('.enc').each(function(){
    	$(this).removeClass('enc').html(decode64(this.innerHTML));

    });

  },function(){

  	$('.main-col:visible a.toggle-all-results span').removeClass('close').html(_('Open all results'));
  	$('.main-col:visible li.has-results .result-open').not('.result-empty div').removeClass('result-open').addClass('result-closed').next('div').hide();

  });
}

function serp_catagoryisreadyOud(id){
//	time.start('Serp Ready '+id);
	$('#'+id+'>a>span.tab-loading').attr('class','tab-done');


	$('div#results-'+id+'>div.button-bar>a.toggle-all-results').toggle(function(){
		$(this).html(_('Close all results')).parent().parent().find('.result-closed').not('.result-empty div').removeClass('result-closed').addClass('result-open').next('div').show();
	},function(){
		$(this).html(_('Open all results')).parent().parent().find('.result-open').not('.result-empty div').removeClass('result-open').addClass('result-closed').next('div').hide();
	});
//	time.stop('Serp Ready '+id);
}

function teaser(obj,msg){
	$('#'+obj).removeClass('result-loading');
  $('#'+obj).find('p,div').html(msg);
}

function noTeaserFound(obj){

	if(obj == 'teaser-img')
		$('#'+obj).attr('class','result-empty').html('');
	else
		$('#'+obj).attr('class','result-empty').html('<p class="teaser-no-result">'+_('no results found')+'</p>');
}

function toggleFieldOnValue(field,value,target) {
	for(i=0;i<target.length;i++) {
		if (field == value)
			$("#" + target[i]).show();
		else
			$("#" + target[i]).hide();
	}
}

function chooseLinkType() {
  if($("a#list-profiles").length > 0) {
    $("a#list-profiles").parent().hide("slow", function(e) {$(e).remove();} );
    $("a.connect-button").parent().hide("slow", function(e) {$(e).remove();} );
  }
	var type = $('#add-link-choose').val();
	if(!type){
		$('#add-link-predefined,#add-link-custom').hide();
		return false;
	}
	switch(type) {
	  case 'hyves':
	  case 'facebook':
    case 'twitter':
	  case 'linkedin':
//  case 'flickr': non-dynamic callback url
//  case 'friendfeed': non-dynamic callback url
//  case 'foursquare': non-dynamic callback url
    case 'youtube':
    case 'netlog':
	  case 'myspace':
  	   $.get("ajax/get_connectbox.php?source=" + type, function(reply) {
  	     $("#add-link-predefined").before(reply.connectbox);
  	     $("#add-link-predefined").before(reply.search_diff);
  	     var dispSerp = false;
  	     attachShowPredefinedResult();
  	   }, "json");
	    break;
	  default:
	     var dispSerp = true;
	   break;
	}

	$(".add-link-choices").hide();
	if (type == 'custom' || type=='feed') {
		$('#add-link-custom').show();
		$("#add-link-custom form:first").show();
		$('#add-link-fields').hide();
	} else {
		$('#add-link-predefined-search a:first').click(function(){
			$('#add-link-predefined-search').hide();
			$('#add-link-predefined form').show();
		})
		if( dispSerp) {$('#add-link-predefined').show();}
		updateLinkFormPredefined();
		initResult('#add-link-predefined');
	}
	return false;
}

function attachShowPredefinedResult() {
  $("a#list-profiles").click(function() {$("#add-link-predefined").fadeIn();$(this).parent("p").hide("slow");})
}

function updateLinkFormPredefined()  {
	var first = $("#add-link-predefined input[name='first']").val();
	var last = $("#add-link-predefined input[name='last']").val();
	var keyword = $("#add-link-predefined input[name='keyword']").val();
	$('#add-link-predefined-content').hide();
	$('#add-link-predefined-loader').show();
	$('#add-link-predefined-content').load('ajax/add_profile_link.php', {
									action: 'load',
									type: $('#add-link-choose').val(),
									first: first,
									last: last,
									keyword: keyword
							}, function(){
								initResult('#add-link-predefined');
								$('#add-link-predefined form').hide();
								$('#add-link-predefined-search').show();
								$('#add-link-predefined-content').show();
								$('#add-link-predefined-loader').hide();
	});
	return false;
}

function addProfileLinkPredefined(id) {
	$.post('ajax/add_profile_link.php', {
			action: 'save',
			type: $("#add_profile_link-" + id + "-type").val(),
			result_id: $("#add_profile_link-" + id + "-rid").val(),
			comment: $("#add_profile_link-" + id + "-comment").val()
		}, function(response){
			$("#profile-add-link-td-" + id + " a").hide();
			$("#profile-add-link-td-" + id + " span").show();
			$("#add_profile_link-" + id + " td").html(response);
			window.location.href = window.location.href;
	});
	return false;
}
function loadCustomLink() {
	if ($("#add-link-custom form:first input[name='url']").val() != '') {
		$('#add-link-url-loader').show();
		$.getJSON('ajax/add_profile_link.php',{
			action: 'load',
			url: escape($("#add-link-custom form:first input[name='url']").val()),
			type: escape($('#add-link-choose').val())}, function(j){
			$('#add-link-custom-error').hide();
			if (j.error) {
				$('#add-link-fields,#add-link-url-loader').hide();
				$('#add-link-custom-error').show();
			} else {
				$("#add-link-custom form:first").hide();
				$('#add-link-custom-error').hide();
				$('#add-link-span-icon').empty();
				if (j.icon)
					$("<img/>").attr("src", j.icon).appendTo("#add-link-span-icon");
				$('#add-link-span-url').html(j.url);
				$('#add-link-span-url-edit').show().click(function(){
					$("#add-link-custom form:first").show();
					$('#add-link-fields').hide();
				});
				//$('#add-link-span-type').html(j.type);
				if (j.title) $("#add-link-fields form input[name='title']").val(j.title);
				if (j.description) $("#add-link-fields form textarea[name='comment']").val(j.description);
				//alert(j.description);
				var options = '';
				if (j.feeds) {
					if (!j.feed) options = '<option value="">'+_('Select a feed to show with this link')+'</option>';
					for (var i = 0; i < j.feeds.length; i++) {
						options += '<option value="' + j.feeds[i] + '">' + j.feeds[i] + '</option>';
			        }
					$('#add-link-feeds select').html(options);
				}
				if (options && !j.feed){
					$('#add-link-feeds').show();
				} else {
					$('#add-link-feeds').hide();
				}
				$('#add-link-fields').show();
				$("#add-link-fields form").show();
				$('#add-link-url-loader').hide();
			}
		},'json');
	}
	return false;
}
function addProfileLinkCustom() {
	$.post('ajax/add_profile_link.php', {
		action: 'save',
		type: 'custom',
		title: $("#add-link-fields form input[name='title']").val(),
		comment: $("#add-link-fields form textarea[name='comment']").val(),
		feed: $("#add-link-fields form select").val()
	}, function(response){
		$("#add-link-fields form").hide();
		$("#add-link-msg").show().html(response);
    window.location.href = window.location.href;
	});
	return false;
}

function selectPopular(){
	$('#search-sources input[type=checkbox]').attr('checked', '');
	$('#search-sources input.popular').attr('checked', 'checked');

	$('.toggle-cat-wrap').each(function(i,n){
		checkboxCheck(n);
	});
	checkboxPopularCheck();
}

function removeThickBoxEvents() {
    $('.thickbox').each(function(i) {
        $(this).unbind('click');
    });
}

function bindThickBoxEvents() {
    removeThickBoxEvents();
    tb_init('a.thickbox, area.thickbox, input.thickbox');
}

function makeCall(type, url, data) {
	if (typeof(data) == 'undefined') {
		data = '';
	}
	var request = $.ajax({
							 		type: type,
									url: url,
									data: data,
									cache: false,
									async: false
								});
	return request['responseText'];
}

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function decode64(input){
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   }while (i < input.length);
   return output;
}

// Nodig?
function rml(d,u){
  ml = 'm'+'a'+'i'+'l'+'t'+'o';
  window.location=ml+":"+u+"@"+d;
}
function emldeobf(e) {
	e = decode64(e);
	var n = '';
	for(i=0;i<e.length;i++) {
		if (!(i%2)) n = n + e.charAt(i);
	}
	n = n.replace(/\\/,'@');
	return n;
}

$.elementReady('profile-details', function(){
	$('.enc').each(function(){
	  $(this).html(decode64(this.innerHTML));
	})

	$('.emobf').each( function(){
		var obf = $(this).attr('href');
		var deob = emldeobf(obf);
		$(this).attr('href','mailto:' + deob);
		$(this).html(deob);
	});

});

function alertCheckIsReady(){
	$('#alert-is-loading').addClass('alert-is-done').find('p').toggleClass('hide');
}

function alertInit(id,name){
	$('#alert-init').html(name)
}

$.elementReady('form-input-single', function(){
	$('#form-input-single>a').click(function(){
		$('#search-form-multi').hide();
		$('#search-form-single').show();
		$('#form-input-multi').removeClass('current');
		$('#form-input-single').addClass('current');
		$('#fullname').focus();
	});
	$('#form-input-multi>a').click(function(){
		$('#search-form-single').hide();
		$('#search-form-multi').show();
		$('#form-input-single').removeClass('current');
		$('#form-input-multi').addClass('current');

		if($('#firstname').hasClass('predefined'))
			$('#firstname').val('').removeClass('predefined');
			$('#firstname').focus();
	});
});

$.elementReady("result-profiles", function() {
  if($("#result-profiles div:first-child").hasClass("result-open")) {
	  $("#result-profiles div.result-content").show();
	}
});


// Additional JS functions

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

/**
 * New functions
 */

$('.more-images-live a').live('click',function(){
  var sHref   = $(this).attr('href');
  var aHref   = sHref.split('#');
  var sParams = aHref[1];
  var oClicked= $(this);

  var base    = $("base").attr('href');
  var sUrl    = encodeURIComponent(sParams);
  $.ajax({
    url: base + 'ajax/moreImages.php',
    cache: false,
    data: ({params: sParams}),
    dataType: 'json',
    success: function(reply, textStatus, xhr) {
      $('.more-images-live').prev('ul').append($(reply.template));
      if(reply.anchor == false || reply.template.length == 0) {
        $(".more-images-live").html('<span>'+_('No more images found')+'</span>');
      } else {
        $(oClicked).attr('href', aHref[0] + '#params=' + reply.anchor);
      }
    }
  });

  return false;
});

/**
 * Show all results under 1 tab
 */
$('.show-all-results|.show-all-results span').live('click',function(){

	$('#searchtypetab li').hide();
	$('#all-result-tab').show();

	//.css('visibility','hidden');
	// ,.result-ad:gt(0) eruit
	$('.serp-title,.serp-pagination,.pagination-info,.result-actions:gt(0),.empty-results:not(:last)').hide();
	$('.main-col:visible').addClass('active-tab');
	$('.main-col').show();
	$('.show-all-results').attr('class','restore-all-results').find('span').html(_('Restore all tabs'));
});

/**
 * Restore tabs
 */
$('.restore-all-results|.restore-all-results span').live('click',function(){
	$('#searchtypetab li').show();
	$('#all-result-tab').hide();

	// ,.result-ad:gt(0) eruit
  $('.serp-title,.serp-pagination,.pagination-info,.result-actions:gt(0)').show();

	if($('.empty-results li').length){
		$('.empty-results').show();
	}
	$('.restore-all-results').attr('class','show-all-results').find('span').html(_('Show all results on one tab'));
	$('.main-col:not(.active-tab)').hide();
	$('.active-tab').removeClass('active-tab');
});


$("#view-wow-ranking").live('change',function() {
	var base 			= $('base').attr('href');
	var country		= $(this).val();
	if(country == '' || country == 'worldwide') {
		window.location.href = base + 'wow-factor-ranking';
	} else {
		window.location.href = base + 'wow-factor-ranking-'+country;
	}
});



function removeTrashLink(p_sQueryStr, p_rElem) {
    if(confirm(_("Whoozy will now check if the source of this result contains the full name of the searched person. If it doesn't, the result will be removed. Press OK to continue."))){
      var queryString = p_sQueryStr;

      //var resultBlock = $(trgt).parents('.result-row-info-open');
      //var resultBlock2 = $(resultBlock).prev('.result-row');
      var resultBlock3 = $(p_rElem).parents('.result-info').parent();

      //alert(queryString);
      $.post('ajax/remove_result.php',queryString,function(response){
        if ( response == 'removed' ) {
          alert(_("Result is removed. Whoozy will no longer show this result."));
          //$(resultBlock).fadeOut();
          //$(resultBlock2).fadeOut();
          $(resultBlock3).fadeOut();
          //window.location.href = window.location.href;
        } else if ( response == 'exist' ) {
          alert(_("Result is NOT removed, because the name is still found at the source."));
        } else if ( response == 'error' ) {
          alert(_("An error occurred. Please try again."));
        } else if( response == 'pageError'){
          alert(_("The page returned an error."));
        }
      });
      return false;
    }
   return false;
}

$('#result-amazon .result-row').live('click', function() {
  var e = $(this).next('tr').find('.link-info');
  if(!$(e).hasClass('wishlist-populated')) {
      $(e).addClass('wishlist-populated');
      var sUrl  = $(e).find('.wishlist-link').attr('href');
      var sHTML = '';
      $.getJSON('ajax/getWishlist.php', {url: sUrl}, function(reply) {
        for(i in reply) {
            sHTML = sHTML + '<li><a rel="external" href="'+reply[i].url+'">' + reply[i].name + '</a></li>';
        }
        $(e).find('.wishlist-list').html(sHTML);

      });
  }
});

// Some analytics tracking Nic requested
$("#search-form-multi form, #search-form-single form, #search-box-company form").live('submit', function() {
  var sCountrySearch = $(this).find('select[name="country"]').val();
  var sType;
  if($(this).find("input[id='company']").length != 0) {
      sType = 'Company';
  } else {
      sType = 'Person';
  }

  if(typeof(_gaq) != 'undefined') {
      _gaq.push(['_trackEvent', 'Searches', sType, sCountrySearch]);
  }
});


$("#country-stats-select").live('change', function() {
  var sCurrent = $('#country-stats-select option[selected="selected"]').val();
  var sNew     = $("#country-stats-select").val();
  var sLocation = window.location.href;

  sLocation = sLocation.replace(sCurrent,sNew);

  window.location.href = sLocation;

});

//show more results (in spider block)
$('.more-results-live').live('click',function(){
	$(this).prev('table').find('tr:hidden:lt(10)').show();
	if (!$(this).prev('table').find('tr:hidden').length) {
		$(this).hide();
	}
});
$(".ad-container-banner-s a").live('click', function() {
  var sHref = $(this).attr('href');
  if(sHref.match(/peopletraceonline\.co\.uk/)) {
    $.get("ajax/clickout.php?type=ad&site=peopletraceonline&url=" + encodeURIComponent(sHref));
  }
});

// measure adsense clickouts
var bHoversAdsense = false;
$("iframe[id*='google']").live('mouseover', function() {
  bHoversAdsense = true;
}).live('mouseout', function() {
  bHoversAdsense = false;
});

$(window).blur(function() {
  if(bHoversAdsense) {
    $.get("ajax/clickout.php?type=ad&site=adsense&url=" + encodeURIComponent(window.location.href));
  }
}).focus();

// the default method for these superbanner links is to log an 'internal external' clickout (and normal logging to ad_clickouts), so lets log something better here:
$("#content-aff-links a").live('click', function() {
  var sSite = $(this).parent('li').attr('id').replace('site-', '');
  var sHref = $(this).attr('href');
  $.get("ajax/clickout.php?type=ad&site="+ sSite +"&url=" + encodeURIComponent(sHref));
});

$("input[type='hidden'][value='1'][name='update'] ~ input[type='submit']").live("click", function() {
  var base = $('base').attr('href');
  var nAjaxCount = 0;

  if(typeof(sTriggerSource) != 'string') {
    $("#profile-details dl:first dd span:not(.stats-total)").each(function() {
      nAjaxCount++;
      var e       = $(this);
      var sSource = $(this).text().toLowerCase();
      sSource = sSource.replace(' ', '');
      var sText   = $(e).next("span.stats-total").text();
      $(e).next("span.stats-total").text(_('updating') + '...');
      $.ajax({
        url: base + 'ajax/updateWow.php',
        cache: false,
        data: ({source: sSource}),
        dataType: 'json',
        success: function(reply) {
          if(reply.value !== false && reply.value.match(/[0-9]+/)) {
            sText = sText.replace(/[0-9]+/, reply.value);
          }
          $(e).next("span.stats-total").text(sText);
        }
      });
    });
  }

  if(typeof(sTriggerSource) == 'string' && sTriggerSource != 'invoke_ajaxstop') {
    nAjaxCount++;
     $.ajax({
      url: base + 'ajax/updateWow.php',
      cache: false,
      data: ({source: sTriggerSource}),
      dataType: 'json',
      success: function(reply) {
        if(typeof(reply.errormsg) == 'string') {
          sDisconnect = reply.source;
          if(sDisconnect == 'facebook') {
            sDisconnect = 'fb';
          }
          $("#connect-" + sDisconnect + " ~ p.connect-info em").remove();
          $("#connect-" + sDisconnect + " ~ p.connect-info strong").after(_("Not connected"));
          $("#connect-" + sDisconnect + " ~ a.connect-options-toggle").remove();
          $("#connect-" + sDisconnect + " ~ div").hide("slow");
          $("#profile-main").prepend('<div class="message message-error"> <p>' + reply.errormsg + '</p></div>');

        }
      }
     });
  }

  if(nAjaxCount == 0) {
     $.ajax({
      url: base + 'ajax/updateWow.php',
      cache: false,
      data: ({invoke_ajaxstop: true})
     });
     // in case a user wants to update his WOW-factor box again after a manual invoke of ajaxstop, make sure to change the type of sTriggerSource (dirty =))
  }

  // update local data
  var bWowRefreshed  = false;
  // final ajax function - make sure  only to execute once
  $("#profile-details").ajaxStop(function() {
    if(bWowRefreshed == false) {
      $.ajax({
          url: base + 'ajax/updateWow.php',
          cache: false,
          data: ({cron: true}),
          dataType: 'json',
          success: function(reply) {
            $('#heading div.wow-badge').replaceWith(reply.badge);
            $("#profile-details").replaceWith(reply.html);

          },
          complete: function() {
            bWowRefreshed = true;
            sTriggerSource= true;
            // complete ALWAYS gets triggered (unlike success) so we insure the server never gets hammered if something fails
          }
      });
    }
  });
  return false;
});


$("#register_form-country").live('change',function() {
  var sVal = $(this).val();
  sVal = trim(sVal);
  if(sVal == 'uk' || sVal == 'us' || sVal == 'it' || sVal == 'fr') {

    var sDomain = sVal;
    if(sVal == 'uk') {
      sDomain = 'co.uk';
    }
    if(sVal == 'us') {
      sDomain = 'com';
    }
    if(sDomain.length == 0) {
      sDomain = 'com';
    }
    $(".kgbdeals-signup a").attr('href', 'http://kgbdeals.' + sDomain);

    if($(".kgbdeals-signup").is(':hidden')) {
      $(".kgbdeals-signup").fadeIn('slow');
      $('#page-home #content, #page-signup #content').equalHeights();
    }
  } else {
    $("input[name='kgbdeals']").attr('checked',false);
    if(!$(".kgbdeals-signup").is(':hidden')) {
      $(".kgbdeals-signup").fadeOut('slow');
      $('#page-home #content, #page-signup #content').equalHeights();
    }
  }
});


function alertLocation(){
		var currentDomain = window.location.hostname.match(/.kgb.+|.wie.+/);
		alert(currentDomain);
}


// Nieuwe "body click trigger"
// Goed testen hoe het met geheugen gaat.
$('body').live('click focus',function(event){
	var blaat = $('li.img,li.tag');
	if(blaat.find('.result-info:visible').length){
		if(!$(event.target).parents('li.img,li.tag').length){
			blaat.css({'z-index' : '0'}).find('.result-info').hide();
		}
	}
});


// Nieuwe Cookie click close
$('.msg-bar a.remove-msg').live('click',function(){
	var cookieToCheck = '__msgbar';
	var msgBar = $(this).parents('.msg-bar');
	var msgBarId = msgBar.attr('id').substr(4);
	var currentDomain = window.location.hostname.match(/kgb.+|wie.+/);
//	alert(currentDomain);
//	return false;
	var cookieValues = $.cookie(cookieToCheck);

	if(cookieValues){
		aCookieValues = cookieValues.split(',');
		aCookieValues.push(msgBarId);
		var sCookieValues = aCookieValues.toString();
	}else{
		var sCookieValues = msgBarId;
	}

	var msgHash = msgBar.attr('class').match(/hash\-(.{32})/);
	if(msgHash){
	  $.post('ajax/message-bar.php', {hash: msgHash[1],msgId : msgBarId});
	}

	$.cookie(cookieToCheck,sCookieValues, {path: '/', expires: 200,domain: currentDomain});
	msgBar.fadeOut();
});

messageBar = function(description,title,type){
	$('body #wrap-content>.msg-bar').remove();

  var html  = '<div class="msg-bar msg-bar-'+type+' hide"><div><p>';
	if(title){
		html += '<strong>'+title+'</strong> ';
	}
	html += description+'</p></div></div>';

 	$('body #wrap-content').prepend(html);
	$('body #wrap-content>.msg-bar').fadeIn();
}

 $('#clear-history').live('click',function(){
	var userhash = $('#clear-history').attr('class').match(/remove\-(.{32})/)[1];

	$.post('./ajax/remove_search_history.php',{hash:userhash}, function(response){
		if(response.status == 'success'){
			$('#dash-searches ul').html('');
			$('#clear-history').hide();
			$('#undo-clear-history').show();
			messageBar('<a href="javascript:void(0)" id="undo-clear-history">'+_('Undo')+'</a>',_('Your history is deleted.'),'ok');
			return false;
		}else{
			messageBar(response.error_message,false,'error');
//			alert(response.error_message); // moet nog wat anders mee worden gedaan
			return false;
		}
	}, 'json');
	return false;

 });


$('#undo-clear-history').live('click',function(){
	var userhash = $('#clear-history').attr('class').match(/remove\-(.{32})/)[1];

	$.post('./ajax/undo_remove_search_history.php',{hash:userhash}, function(response){
		if(response.status == 'success'){
			$('#dash-searches ul').html(response.html);
			$('#clear-history').show();
			$('#undo-clear-history').hide();
			messageBar(_('Your history has been restored.'),false,'ok');
			return false;
		}else{
			messageBar(response.error_message,false,'error');
			return false;
		}
	}, 'json');

	return false;
});

(function($){var queue=[],interval,check=function(){for(var i=0;i<queue.length;i++){if($(queue[i][0])[0]&&(queue[i][2]||$(queue[i][0]).next()[0]||$.isReady)){try{queue[i][1].apply($(queue[i][0]).eq(0));}catch(e){if(typeof console!='undefined'){console.log(e);}}queue.splice(i,1);i--;}}if(!queue.length||$.isReady){interval=clearInterval(interval);}};$.fn.available=function(fn,turbo){turbo=turbo||false;queue.push([this.selector,fn,turbo]);if(!interval){interval=setInterval(check,1);}return this;};})(jQuery);

$('#wrap-footer').available(function(){
	if($('body').hasClass('person')){
		var data = $('#search-bar form').serialize();
		$.get('./ajax/getSuperBanner.php',data,function(html){
			if(html){
				$('#content .main-col:first ul.results li.result-ad:last').before(html);
			}
		});
	}
});


function FbIsLoggedIn() {
 	FB.getLoginStatus( function(response) {
	  if (response.status == 'connected') {
		return true;
	  } else {
 	  	return false;
	  }
	});
}


function FbLoginAndBuild(){
	// if(FbIsLoggedIn()) { 
		$('#fb-profile-build').trigger('click'); 
	// }
}

$('#result-relatieplanet a').live('click',function(){
	$(this).attr('target','_blank');
});



