/**
 * Settings
 */

var preDefined = new Array();
		preDefined['fullname'] = _('Firstname')+' '+_('Lastname');
		preDefined['firstname'] = _('Firstname');
		preDefined['lastname'] = _('Lastname');
		preDefined['company'] = _('Company');
		preDefined['keyword'] = _('e.g. city');

var primary = new Array('firstname','fullname','company');

/**
 * 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;
  };
}

// Jquery document ready
$(function() {

  // 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 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');
  });

  //css3 for non-standard browsers
  $('.nav-sec dd:last-child').css('border', '0');

  //tabs arrow
  $(".tabs li.current").append("<strong></strong>");

  //add class to remove margin
  $('.faq div p:last-child').addClass('p-last');
  $('.index-names ul:last-child').addClass('ul-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"
    }
  });

  //lightbox voor T&C
  if ($("a.iframe").html()) $("a.iframe").fancybox();

  $('.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(){
      checkboxCheck(n);
      checkboxPopularCheck();
    })
  });

  // Advanced search Cat check
  $('.toggle-cat-wrap > input').click(function(){
    if($(this).attr('checked')){
      $(this).parent().next().find('input[type=checkbox]').attr('checked','checked');
    }else{
      $(this).parent().next().find('input[type=checkbox]').attr('checked','');
    }

    checkboxPopularCheck();
  });



  //$('#profile-sites').dragsort({ dragSelector: ".profile-link-li" });

  //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()
  },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();
  });

  //autocomplete
  $("#fullname").autocomplete(
			"ajax/autocomplete_name.php",
			{
				delay:400,
				minChars:3,
				matchSubset:0,
				matchContains:1,
				cacheLength:10,
				scroll:false,
				width:502,
				selectFirst:false
				//formatItem:formatItem,
				//autoFill:true
			}
//		).focus();
		);

	 // 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="..." />');
    $.get("ajax/disconnect_profile?source=" + source[1], 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");
      }
    }, "json");
  });

  $('#page-home #search-form-multi').not('.hide').find('#firstname').focus();
  $('#page-home #search-form-single').not('.hide').find('#fullname').focus();

  $("a.verify-wow-site").click(function() {
    var e = $(this);
    verifyWowSite(e)
  });

  $("a.disconnect-verified-site").click(function() {
    var e = $(this);
    disconnectVerifiedSite(e);
  });
// Shorten 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');
  }

  $('#settings-input input').click(function(){
  	var checked = $('#settings-input input:checked').attr('id').substr(6);
  	$('#search-bar>div').hide();
  	$('#search-form-'+checked).show();
  });


  $('#page-home #form-search-options a:last').click(function(){
  	$('#search-box>div').toggle();
  	return false;
  }).toggle(function(){
  	// Company
  	$('.main-col h1').html(_('Looking for company info? Start your search here.')).hide().fadeIn(600);
		$('#form-search-options .link-settings').attr('href',dgettext('url','search-settings-company'));
		$('#form-search-options .company-search').attr({'href':'/','class':'persons-search'}).html(_('People search'));
		$('#search-box-company input:first').focus();

  },function(){
  	// Persons
		$('.main-col h1').html(_('Looking for someone? Start your search here.')).hide().fadeIn(600);
		$('#form-search-options .link-settings').attr('href',dgettext('url','search-settings'));
		$('#form-search-options .persons-search').attr({'href':dgettext('url','company-search'),'class':'company-search'}).html(_('Company search'));
		$('#search-box-persons input:first').focus();
  });

	// Searchsettings -> select popular sources
  $('#source-select-popular').click(function(){
		selectPopular();
  });

  // Searchsettings -> select all
  $('#source-select-all').click(function(){
    $('#search-sources').find('input[type=checkbox]').attr('checked','checked');
  });

  // Searchsettings -> select none
  $('#source-select-none').click(function(){
		$('#search-sources').find('input[type=checkbox]').attr('checked','');
  });


  $('#search-settings-form').submit(function(){

  	var doReturn =  checkSearchForm($('#search-bar form:visible'));
  	return doReturn;
  });

  checkboxPopularCheck();
//end of document-ready
});


/**
 * Adds the click on the "more countries in the footer and shows only the top 5 countries
 */
$.elementReady('footer',function(){
 //toggle countries list
  $('#country-list dd:gt(4):not(dd#toggle-countries)').hide();
  $("dd#toggle-countries a").click(function () {
    $('#country-list dd:gt(4):not(dd#toggle-countries)').slideToggle();
    $(this).text($(this).text() == _('More countries') ? _('Show less') : _('More countries'));
    $(this).parent('dd').toggleClass('toggle-less');
    return false;
  });
});

/**
 * 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(){

  	var doReturn = checkSearchForm($(this));
  	if(doReturn && $('#search-settings-form').length){
	    $('#search-settings-form').submit();
	    return false;
	  }
	  return doReturn;
  });

  $('.search input[type="text"]').focus(function(){

    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] && $.trim(v))
        doReturn = true;
      else
        return false;
    }else{
      if(doReturn && (v == preDefined[i])){
        c.val('');
        v = '';
      }
    }
    $('#search-settings-form #fill_'+i).val(v);
  });

  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();
   }, "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");
}



// 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){
	if($(n).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(){
  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','');
 }
}

/*
$('#search-sources li input[type=checkbox].popular:checked').length;

$('#search-sources li input[type=checkbox]:checked').not('.popular').length;

*/

// 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 opgebouwt zijn doormiddel van tabellen.
  if($(trgt).is('table tr.result-row, table tr.result-row *') && trType != 'a'){
    $(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 currentLi = $(trgt).parents('li');

    if($(currentLi).hasClass('result-ad') || $(currentLi).hasClass('result-empty'))
      return;


    $(currentLi).hasClass('empty')
      addContentToSpider(currentLi);

    $(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' : '9998'}).find('.result-info').css({'z-index' : '9999'}).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');
        }
      }

      // Remove the result
      if($(trgt).parent().hasClass('trash-link')){
        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 = $(trgt).attr('href');
          //var resultBlock = $(trgt).parents('.result-row-info-open');
          //var resultBlock2 = $(resultBlock).prev('.result-row');
          var resultBlock3 = $(trgt).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;
      }

    	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();

				  $('.add-link-from-results').html('');
			  	$(resultblock).find('.add-link-from-results').html($('#add-link-from-results').html());

		  		var url = $(trgt).attr('href');

	  			$('.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 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');

						$.get('ajax/clickout.php',{'url' : clickhref,'id':clickid});
	      }
      }

   // 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) {
			//alert(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");
					}
		});
	}
}

$.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('serp', function(){
});


function paginate(id){
  switchToTab(id);
  $('html,body').animate({scrollTop: (0)}, 0,false,function(){});
}

function TabClick(id) {
	var tabId = $(id).parent("li").attr("id");
	switchToTab(tabId);
}

function scroller(location){  var position=$(location).offset();
  $('html,body').animate({scrollTop: (position.top-20)}, 500,false,function(){});
}

$.elementReady('nav', function(){
  $('#login-error').hide();

/**
 * Login box and language box
 */
  $('.dropbox').click(function(){
  	var clickedBox = $(this).attr('id').substr(8);
  	var clicked = $('#'+clickedBox);

  	clicked.slideToggle('fast');

  	if(clicked.hasClass('opened')){
  		clicked.removeClass('opened');
  	}else{
  		if(clickedBox == 'loginbox'){
  			 $('#useremail').focus();
  		}

  		$(document).mouseup(function(e) {
  			if($(e.target).attr('id') != 'clickedBox' && (!$(e.target).parents('#'+clickedBox).length) && ($(e.target).attr('id') != 'dropbox-'+clickedBox) && (clickedBox != $(e.target).attr('id'))){
					clicked.hide();
  			}
  		});
  		clicked.addClass('opened');
  	}
  });

/**************************************************/


  $('#loginform,#loginform2').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) {
        $('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);
          $('#myprofile').attr('href','./'+data.profile_url).html(data.profile_name);
          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;
var currentTab;

function switchToTab(tabId){

	if(!currentTab)
		currentTab = $('div#searchtypetab>ul>li.current').attr('id');

	$('#'+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;
}

// 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" });
});

$.elementReady('filters',function(){
	$('#filter-keyword').focus(function(){
	    if($(this).val() == _('enter keyword'))
	      $(this).removeClass('predefined').val('');
	  }).blur(function(){
	    if($(this).val() == ''){
	      $(this).addClass('predefined').val(_('enter keyword'));
	    }
	  });
	$('#filters form').submit(function(){
		if($('#filter-keyword').val() == _('enter keyword')){
			$('#filter-keyword').val('');
		}
		window.location = $(this).attr('action') + '&keyword=' + $('#filter-keyword').val();
		return false;
	});
});
/************* 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);
}

function copyFoundToResults(id){
	var divname='result-'+id;
	var newdiv='found-'+id;document.getElementById(divname).innerHTML=document.getElementById(newdiv).innerHTML;
}

function removeAddVerified(){
	$('#add-verfified').remove();
}

var noEmptyResults = true;
function hideEmptyResult(id,name){
	if(noEmptyResults)
		$('#empty-results').show();

	noEmptyResults = false;

	noResultsFound(id);
	$('#result-'+id).fadeOut('slow');
	$('#empty-results ul').append('<li>'+name+'</li>');
}

function noResultsFound(id){
	switch(id){
		case 'places':
		case 'keywords':
			$('#result-'+id+' p').attr('class','result-empty').html(_('no results found'));
		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'));
}

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');
    $(elm).find('.enc').each(function(){
    	$(this).html(decode64(this.innerHTML));
    });
  }
}


function serp_catagoryisready(id){
  // Category is ready, add a check beside the name
	$('#'+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+'>div.button-bar>a.toggle-all-results').toggle(function(){
    $(this).find('span').addClass('close').html(_('Close all 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()
  },function(){
    $(this).find('span').removeClass('close').html(_('Open all results'));

    $(currentCategory).find('.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 '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');
}


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();
	}
});
