var ajaxTimeout = null;
var orderBy     = '';

$(document).ready(function() {
	$(".ui-dialog-titlebar-close").unbind('mouseenter');
   addPersonEventHandlers();
   advancedSearch();


   Emailer = new Emailer();
   Group   = new Group();
   Group.addPlusToGroupFolders();
   Group.detectActiveGroup();

});

$(window).bind("load scroll", function() {

	var scrolled = $('html').scrollTop() + $(window).height();
	var offset;
	var displayThreshold;

	$('.person-list-current-location li').each(function(){

	    offset = $(this).offset();
	    displayThreshold = offset.top - 3 * $('.business-card').height();

	    if (scrolled > displayThreshold && !$(this).hasClass('loaded')){

	        profileId = $(this).parents('.business-card').attr('rel');
	        displayCurrentLocation (this, profileId);
	        $(this).addClass('loaded');

	    }

	});

});


function displayCurrentLocation (listitem, profileId)
{

	$.ajax({
		url      : 'fileadmin/template/ajax/fetchlocation.php',
		type     : 'POST',
		data     : 'profile_id=' + profileId,
		success  : function(locationLink) {
			$(listitem).text(locationLink);
		},
		error    : function(ajaxObject,text,error) {
			$(listitem).text('ikke tilgængelig');
		}
	});

}

function addPersonEventHandlers()
{

	updateGroupLinks();

	updatePagination();

	toggleNavigationVisibility();

	advancedsearchViewSwitcher();

    $("#display-listview").live('click', function() {
    	displayListView();
    });

    $("#display-profileview").live('click', function() {
    	displayProfileView();
    });

    if(getActiveDisplay() == 'business-card') {
    	deactivateEmailSendout();
    }else	{
    	activateEmailSendout();
    }

    $("#email_check img").live('click', function() {
		var checked   = $("#profile-list").find('input[type="checkbox"]:checked').length;
    	var unchecked = $("#profile-list").find('input[type="checkbox"]').length - checked;

    	if(checked <= unchecked) {
    		$("#profile-list").find('input[type="checkbox"]').attr('checked', 'checked');
    	}else	{
    		$("#profile-list").find('input[type="checkbox"]').attr('checked', '');
    	}

    });

    $(".submit-captcha-button").live('click', function() {
       var challenge = Recaptcha.get_challenge();
       var response  = Recaptcha.get_response();
       var profileId = $(this).attr('rel');

       $.ajax({
            url      : 'fileadmin/template/ajax/fetchemails.php',
            type     : 'POST',
            dataType : 'json',
            data     : 'challenge=' + challenge + '&response=' + response + '&profile_id=' + profileId,
            success  : function(json) {

                    if(json.result == 'success' && json.challenge == 'passed') {
                        document.cookie='is_human' + "=" + 'true';
                        $("#recaptcha-placeholder").remove();
                        location.reload();
                    }else if(json.result == 'success' && json.challenge == 'failed') {
                        Recaptcha.reload();
                        $(".submit-captcha-button").addClass('active negative').text('Forkert. PrÃ¸v igen');
                        $("#recaptcha_response_field").val('');
                    }
            },
            error    : function(ajaxObject,text,error) {

            }
        });
    });

    $("img#close-captcha").live('click', function() {
       $("#recaptcha-placeholder").remove();
       $("#fader").remove();
    });

    $("#recaptcha_response_field").live('keyup', function(e) {

        if(e.keyCode == 13) {
            $(".submit-captcha-button").click();
        }

        if($('.submit-captcha-button').hasClass('negative')) {
            $(".submit-captcha-button").removeClass('active negative').text('Vis email');
        }

    });

    $(".show-all").live('click', function() {
       toggleActionMenu($(this));
    });

    $(".person-list-email-list li.initiat-show-email").live('click', function(e) {

		var profileId = $(this).closest('li.business-card').attr('rel');

		attachCaptcha(profileId, e);

    });

    $("#profile-list td.initiat-show-email a").live('click', function(e) {

    	var profileId = $(this).parent('td').attr('rel');

    	attachCaptcha(profileId, e);

    });

}


function attachCaptcha(profileId, event)
{

     $('<div id="fader"></div>').appendTo("#column-main");

     $('<div id="recaptcha-placeholder"></div>')
          .html('<img id="close-captcha" src="fileadmin/template/images/icons/close_gray.png" alt="luk" /><div id="captcha"></div><a rel="' + profileId + '" class="button submit-captcha-button" href="javascript:void(false);">Vis email</a>')
          .appendTo('body')
          .hide()
          .css({
              'position': 'absolute',
              'top'     : event.pageY - 35,
              'left'    : event.pageX - 115

          })
          .fadeIn('fast');

      Recaptcha.create("6Lce27oSAAAAABqlGPapouHTLkB0qvtqfNP1_5Pk",
          "captcha", {
                  theme: "white",
                  custom_translations : {
                      visual_challenge : "FÃ¥ et nyt billede",
                      audio_challenge : "FÃ¥ et nyt lydbaseret spÃ¸rgsmÃ¥l",
                      refresh_btn : "FÃ¥ et nyt billede",
                      instructions_visual : "Indtast de to udtryk",
                      instructions_audio : "Indtast hvad du hÃ¸rer",
                      help_btn : "HjÃ¦lp",
                      play_again : "Spil lyden igen",
                      cant_hear_this : "Download lyd som mp3",
                      incorrect_try_again : "Forkert. PrÃ¸v igen"
                  },
                  callback: Recaptcha.focus_response_field
          }
      );

}


function updateGroupLinks()
{

//	var doDisplay = getActiveDisplay();
//
//	if($(".person-groups a").eq(0).attr('href').search(doDisplay) !== -1) {
//		return false;
//	}
//
//	if(doDisplay == 'business-card') {
//	    var	doNotDisplay = 'profile-list';
//	}else	{
//	    var doNotDisplay = 'business-card';
//	}
//
//	$(".person-groups a").each(function() {
//
//		$(this).attr('href', $(this).attr('href').replace("&display=" + doNotDisplay, "") + '&display=' + doDisplay);
//
//	});

//	alert(getParameter('display'));
	$(".person-groups a").each(function() {

		if ($('#business-cards').hasClass('hidden')){

			$(this).attr('href', $(this).attr('href') + "&display=profile-list");

		} else {

			$(this).attr('href', $(this).attr('href').replace("&display=profile-list", ""));

		}

	});

}


function updatePagination()
{

	var disablednav = '';
	var page = getParameter('page');
	var lastpage = $('.pagination-control .pagination-nav.last').attr('rel');

	if (page < 2){

		disablednav = 'span.pagination-nav.first, span.pagination-nav.previous';

	}

	if (page == lastpage){

		disablednav = 'span.pagination-nav.next, span.pagination-nav.last'

	}

	$(disablednav).each(function(){

		var navtext = $(this).children().text();
		$(this).text(navtext);
		$(this).addClass('disabled');

	});

}


function toggleNavigationVisibility(){

	$('#display-listview').live('click', function(){

		$('.pagination-control').addClass('hidden');

	});

	$('#display-profileview').live('click', function(){

		$('.pagination-control').removeClass('hidden');

	});

	if ($('#business-cards').hasClass('hidden')){

		$('.pagination-control').addClass('hidden');

	} else {

		$('.pagination-control').removeClass('hidden');

	}

}


function advancedsearchViewSwitcher(){

	$('#advanced-result-tabs li').click(function() {

	    $(this).siblings().removeClass('active-tab');

	    $(this).addClass('active-tab');

	    $('#personlist, #advancedsearch').toggle();

	});

}

function getActiveDisplay()
{

	var doNotDisplay = $(".hidden").attr('id');

    switch(doNotDisplay) {

    	case 'business-cards':

    		var doDisplay = 'profile-list';

    		break;

    	case 'profile-list':

    		var doDisplay = 'business-card';

    		break;

    }

    return doDisplay;

}


function displayProfileView()
{
	$("#profile-list").fadeOut('fast', function() {
		$("input#display").val('business-card');
		$(this).addClass('hidden');
		$("#business-cards").fadeIn('fast').removeClass('hidden');
		updateGroupLinks();
		$("img.sendout-image").attr('src', 'fileadmin/template/images/icons/mail_14x11_gray.png');
		$("img.reload-all-image").attr('src', 'fileadmin/template/images/icons/reloadall_gray.png');
		$("#send-email-link").addClass('inactive-email-sendout');
		$("#show-all-link").addClass('inactive-email-sendout');
	});
}


function displayListView()
{
	$("#business-cards").fadeOut('fast', function() {
		$("input#display").val('profile-list');
		$(this).addClass('hidden');
		$("#profile-list").fadeIn('fast').removeClass('hidden');
		updateGroupLinks();
		//$("img.sendout-image").attr('src', 'fileadmin/template/images/icons/mail_16x12.png');
		//$(".inactive-email-sendout").removeClass('inactive-email-sendout');
		activateEmailSendout();
	});
}


function activateEmailSendout()
{

	$("img.sendout-image").attr('src', 'fileadmin/template/images/icons/mail_16x12.png');
	$("img.reload-all-image").attr('src', 'fileadmin/template/images/icons/reloadall.png');
	$(".inactive-email-sendout").removeClass('inactive-email-sendout');

}


function deactivateEmailSendout()
{

	$("img.sendout-image").attr('src', 'fileadmin/template/images/icons/mail_14x11_gray.png');
	$("#send-email-link").addClass('inactive-email-sendout');
	$("#show-all-link").addClass('inactive-email-sendout');

}


function manageSpinner(action, callback, remove)
{

    if(remove === undefined) {
        remove = true;
    }

    switch (action) {

        case 'show':

            var mininumHeight = $("#column-main").height();

            $("#column-main").css('min-height', mininumHeight + "px");

            $("#create-mailinglist").remove();

            $(".person-list").hide();
            $("#profile-list").hide();
            if(remove) {
                $(".person-list").remove();
                $(".pagination-control").remove();
                $("#displaytype-menu").remove();
                $("#profile-list").remove();
                $("#business-cards").remove();
            }else   {
                $(".pagination-control").hide();
                $("#displaytype-menu").hide();
            }

            $('<div class="person-list-spinner"></div>')
                .html('<img src="fileadmin/template/images/spinners/ajax-loader-personlist.gif" />')
                .insertAfter('#breadcrumb');
            if(callback !== undefined){
                callback.call();
            }

            break;

        case 'hide':
                $(".person-list-spinner").eq(0).fadeOut('fast', function() {

                    $(".person-list-spinner").remove();
                    if(callback !== undefined) {
                        callback.call();
                    }
                });

            break;

    }

}


function Emailer()
{

	this.checkboxes = 0;
	this.checkedCheckboxes = 0;

	// Initialize the click
	this.init = function()
	{
		// Show all search results
		$("#show-all-link").live('click', function() {
			Emailer.turnPaginationOff();
 			performAjaxSearch();
    	});


    	// Send email
    	$("#send-email-link").live('click', function() {

            var profileIds = "";

            $(".email-checkout:checked").each(function() {
                var id      = $(this).closest('tr').children('td.email').text();
                profileIds += id + ";";
            });

            if (profileIds.length > 1000){

                $("#email-dialog").html("<textarea>" + profileIds + "</textarea>");

                $("#email-dialog").dialog({
                        modal   : true,
                        width   : 420,
                        title   : translate('Copy/paste disse emails ind i din email klient', 'Copy/paste these emails into your email client')
                });

            } else {

                $("#send-email-link").attr('href', 'mailto:' + profileIds);

            }
//
//    		if(Emailer.emailsAboveLimit()) {
//    			//Emailer.offerToIncludeAllEmails();
//    			Emailer.listSelectedEmails();
//    		}else	{
//    			Emailer.fetchSelectedEmails('link');
//    		}
//
    	});

    	// Close dialog
    	$("#email-actions .negative").click(function() {
    		Emailer.closeDialog();
    	});

    	// Generate text file
    	$("#create-text-file").click(function(){
    		//Emailer.fetchSelectedEmails('file');
    		Emailer.appendIdsAsParameters();
    	});


	}

	this.listSelectedEmails = function()
	{
		var emails = "";

		$(".email-checkout:checked").each(function() {
			emails += $(this).parent('td').siblings(".email").children("a").text() + ";";
		});

		$("#email-dialog").html("<textarea>" + emails + "</textarea>");

		$("#email-dialog").dialog({
			modal   : true,
			width   : 420,
			title   : translate('Copy/paste disse emails ind i din email klient', 'Copy/paste these emails into your email client')
		});

		$("#email-dialog textarea").select();
	}

	this.appendIdsAsParameters = function()
	{
		var ids = "";
		$(".email-checkout").each(function(){

			ids += $(this).val() + ",";

		});

		$("#create-text-file").attr('href', $("#create-text-file").attr('href') + ids);

	}

	this.closeDialog = function()
	{
		$("#email-dialog").dialog('close');
	}

	this.emailsAboveLimit = function()
	{
		var text = "";
		$(".email-checkout:checked").each(function(){
			text += $(this).val();
		});

		if(text.length > 1000) {
			return true;
		}

		return false;
	}

	this.turnPaginationOff = function()
	{
		$("#paginate").val('false');
	}

	this.clearCurrentEmailLink = function()
	{
		$("#send-email-link").attr('href', '');
	}

	this.fetchSelectedEmails = function(type)
	{
		var profileIds = "";

        $(".email-checkout:checked").each(function() {
            var id      = $(this).val();
            profileIds += id + ",";
        });

        $.ajax({
            url:      'fileadmin/template/ajax/fetchmailinglist.php',
            type:     'post',
            dataType: 'json',
            data:     'profiles=' + profileIds + '&type=' + type,
            success:  function(json) {

               	if (type == 'link') {
               		Emailer.generateMailtoLink(json);
               	}else if(type == 'file') {
               		Emailer.displayFileDownloadSuccess();
               	}

            }
         });
	}

	this.generateMailtoLink = function(json)
	{
		 Emailer.clearCurrentEmailLink();
         $("#send-email-link").attr('href', 'mailto:' + json.emails.join(';'));
         document.location = $("#send-email-link").attr('href');
	}

	this.displayFileDownloadSuccess = function()
	{

	}

	this.offerToIncludeAllEmails = function()
	{
		$("#email-dialog").dialog({
			modal   : true,
			width   : 420,
			title   : translate('Du har valgt for mange emails', 'You have selected too many emails')
		});

		Emailer.appendIdsAsParameters();
	}

	this.init();
	return true;

}


function Group()
{

	this.init = function()
	{
		$("#person-search").focus(function() {
			Group.displayExplanation();
		});

		$("#person-search").blur(function() {
			Group.hideExplanation();
		});

		$(".fold-groups").live('click', function() {
			Group.toggleGroups($(this).parent());
		});

	}

	this.addPlusToGroupFolders = function()
	{
		$(".person-groups .main").each(function(){
			$('<span class="fold-groups">+</span>').prependTo($(this));
		});
	}

	this.toggleGroups = function(object)
	{

		if (object.hasClass('open')) {
			Group.closeGroups(object);
		}else	{
			Group.openGroups(object);
		}
	}

	this.openGroups = function(object)
	{
		object.children('span').text('-');
		object.nextUntil("li:not(.sub)").css('display','list-item');
		object.addClass('open');
	}

	this.closeGroups = function(object)
	{
		object.children('span').text('+');
		object.nextAll("li.sub").css('display','none');
		object.removeClass('open');
	}

	this.displayExplanation = function()
	{
		if($("#group-explanation").length > 0) {
			$("#group-explanation").fadeIn('fast');
		}
	}

	this.hideExplanation = function()
	{
		if($("#group-explanation").length > 0) {
			$("#group-explanation").fadeOut('fast');
		}
	}

	this.detectActiveGroup = function()
	{

		if ($(".personlist-group-name").length == 1) {
			var id = getParameter('gid');
			Group.markActiveGroup(id);
		}

	}

	this.markActiveGroup = function(groupId)
	{

		$(".person-groups li a").each(function() {

			if ($(this).attr('rel') == groupId) {

				var object = $(this);

				object.css('font-weight', 'bold');

				if (object.parents('li').hasClass('sub')) {

					Group.openGroups(object.parents('li').prevAll(".main").first());

				}

			}

		});

	}

	this.init();
	return true;

}


function getParameter(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


function advancedSearch()
{
	updateCriteriaVisibility(0);

	$('.personsearch-categorycheckbox').change( function() {

		if ($(this).is(':checked')) {

			$('#personsearch-list-' + $(this).attr('name')).slideDown();

		} else {

			$(this).parent().parent().parent().find('.personsearch-groupcheckbox').attr('checked', false);
			$(this).parent().parent().parent().find('.personsearch-input').attr('value', '');
			$('#personsearch-list-' + $(this).attr('name')).slideUp();

		}

	});

	$("input:checkbox").change( function () {
		updateCriteriaVisibility(750);
	});

	$('.personsearch-criteria').each( function(index) {

		if ($(this).attr('rel') != '') {
			$(this).hide();
		}

	});

}


function updateCriteriaVisibility(slidespeed) {

	$('.personsearch-criteria').each( function(index) {

		if ($(this).attr('rel') != '') {

			var criteria = $(this).attr('rel').split(" ");

			var visible = false;

			for (var i in criteria) {

				if ($('#checkbox-' + criteria[i].substr(1)).is(':checked')) {

					if (criteria[i].substr(0,1) == '+') {

						visible = true;

					} else if (criteria[i].substr(0,1) == '-') {

						visible = false;

					}

				}

			}

			if (visible) {

				$(this).slideDown();

			} else {

//				$(this).find('#personsearch-text .personsearch-input').val('');  // Remove input from textsearch field
				$(this).find('.personsearch-groupcheckbox').attr('checked', false);
				$(this).find('.personsearch-list').hide();
				$(this).find('.personsearch-categorycheckbox').attr('checked', false);
				$(this).find('.personsearch-categorycheckbox').attr('checked', false);
				$(this).slideUp(slidespeed);

			}

		}

	});

}
