$(function() {
    // Client-side prefs
    var preferences = new function() {
	var DEFAULTS = {};
	var data = null;
	  
	function load() {
	    if (data === null) {
		var json = $.cookie('lots');
		if (json !== null) {
		    try {
			data = $.evalJSON(json);
		    } catch(e) {
		    }
		}
		if (data === null) {
		    data = DEFAULTS;
		}
	    }
	}

	function save() {
	    $.cookie("lots", $.toJSON(data), { expires: 365, path: "/" } );
	}
	
	this.get = function(key, dflt) {
	    var ret;
	    load();
	    if (typeof(data[key]) !== "undefined") {
		ret = data[key];
	    } else {
		ret = dflt;
	    }
	    return ret;
	}
	this.set = function(key, value) {
	    load();
	    data[key] = value;
	    save();
	}
    }();

    // Groups panel
    (function() {
	function isPanelOpen(panel) {
	    return $("ul.lot-group", panel).is(":visible");
	}
	function openPanel(panel, instant) {
	    var el = $("ul.lot-group", panel);
	    if (instant) {
		el.show();
	    } else {
		    el.slideDown();
	    }
	    $(".lot-panel-lid", panel).html("&#9660");
	}
	function closePanel(panel) {
	    $("ul.lot-group", panel).slideUp();
	    $(".lot-panel-lid", panel).html("&#9658");
	}
	var groupsPanel = $("#lot-groups-panel");
	$("h4", groupsPanel).click(function() {
	    var panel = $(this).closest(".lot-group-panel");
	    if (isPanelOpen(panel)) {
		closePanel(panel);
	    }
	    else {
		preferences.set("group", panel.data("group"));
		openPanel(panel);
		$.each(groupsPanel.find(".lot-group-panel").not(panel),
		       function(i, el) {
			   closePanel($(el));
		       });
	    }
	});
    })();
    
    // Secret lot
    (function() {
	$(".lot-secret a.lot-reveal, .lot-secret .participant_avatar").click(function() {
	    var div = $(this).closest(".lot-secret");
	    var realImg = div.find(".participant_avatar");
	    var link = div.find(".lot-secret-link");
	    if (realImg.is(":visible")) {
		realImg.fadeOut();
		link.fadeOut();
		
	    } else {
		realImg.fadeIn();
		link.fadeIn();
		var landing = div.closest("#lot-retrieve-landing");
		if (landing.length) {
		    $.ajax({ url: window.location.href,
			     type: "post",
			     data: { lot: landing.data("lot") }
			   });
		}
	    }
	    return false;
	});
    })();
});

function participantsForm() {
$(function() {
    var participantCountField = $("input[name='participant_count']");

    function participantCount(cnt) {
	var ret =  participantCountField.attr('value');
	if (cnt) {
	    participantCountField.attr('value', cnt);
	}
	return parseInt(ret);
    }

    function participantRow(y) {
	return $('#participant_row_'+y);
    }

    function elementToParticipantNr(elt) {
	var rid = $(elt).parents('tr').attr('id');
	var parts = rid.split('_');
	return parts[parts.length-1];
    }


    function moreParticipants() {
	var cnt = participantCount();
	var row = participantRow(cnt);
	if (row.length > 0) {
	    cnt++;
	    participantCount(cnt);
	    row.fadeIn();
	updateMoreLessButtons();
	}
	return false;
    }

    function updateMoreLessButtons() {
	var cnt = participantCount();
	$('#participants_less').attr("disabled", cnt <=3);
    }

    function updateParticipantTooltip(participantNr) {
	var tt = getParticipantTooltip(participantNr);
	$(".lot-participant-avatar-"+participantNr).attr("title", tt);
    }

    function lessParticipants() {
	var cnt = participantCount();
	if (cnt > 3) {
	    var p = cnt-1;
	    var row = participantRow(p);
	    row.find('input').attr('value', '');
	    for (var i = 0; i < cnt; i++) {
		setBlocked(p, i, false);
		setBlocked(i, p, false);
		getParticipantBlockAvatar(p, i).remove();
		getParticipantBlockAvatar(i, p).remove();
	    }
	    row.hide();
	    participantCount(cnt-1);
	}
	updateMoreLessButtons();
	return false;
    }


    function setBlocked(participant, blockCandidate, block) {
	var cb = getBlockCheckbox(participant, blockCandidate);
	cb.attr('checked', block);
    }

    function isBlocked(participant, blockCandidate) {
	if (participant == blockCandidate) {
	    return true;
	}
	return getBlockCheckbox(participant, blockCandidate).attr('checked');
    }

    function getBlockCheckbox(participant, blockedParticipant) {
	return $("#id_participant_block_"+participant
		 +'_'+blockedParticipant);
    }

    function getParticipantTooltip(participantNr) {
	var tr = $("#participant_row_"+participantNr);
	var name = $(".lot-participant-name input", tr).val();
	var email = $(".lot-participant-email input", tr).val();
	var ret = "";
	if (name) {
	    ret = name;
	}
	if (email) {
	    var a = name ? " <": "<";
	    ret = ret +a + email + ">";
	}
	return ret;
    }

    function getParticipantAvatarUrl(participantNr) {
	var tr = $("#participant_row_"+participantNr);
	var email = $(".lot-participant-email input", tr).val();
	if (! email) {
	    email = ""+participantNr;
	}
	var hash = MD5(email);
	var base = "http://www.gravatar.com/avatar/";
	var fullUrl = base+hash +"?d=wavatar&s=32";
	return fullUrl;
    }

    function getParticipantBlockAvatar(participant, blockedParticipant) {
	return $('#participant_block_avatar_'+participant
		 +'_'+blockedParticipant)
    }

    function removeBlock(participant, blockedParticipant) {
	if (isBlocked(participant, blockedParticipant)) {
	    setBlocked(participant, blockedParticipant, false);
	    getParticipantBlockAvatar(participant, blockedParticipant)
		.fadeOut(function () {
			$(this).remove();
			var row = $("#participant_row_"+participant);
			if (row.find(".participant_block_avatar").length == 0) {
			    $(".lot-participant-drag-hint", row).show();
			}
		    });

	}
    }

    function addBlock(participant, blockedParticipant, isInit) {
	if (participant == blockedParticipant) {
	    alert(strExcludeSelf);
	    return;
	}
	if (!isInit && isBlocked(participant, blockedParticipant)) {
	    alert(strAlreadyExcluded);
	    return;
	}
	setBlocked(participant, blockedParticipant, true);
	var dropTarget = $("#participant_row_"+participant+" .participant_blocks");
	var blockedImg = $("#participant_row_"+blockedParticipant+" .participant_avatar_drag");
	var avatarUrl = getParticipantAvatarUrl(blockedParticipant);
	var blockedElt = $('<img id="participant_block_avatar_'
	    +participant+'_'+blockedParticipant
	    +'" class="participant_block_avatar lot-participant-avatar-'+blockedParticipant+'" src="'
			   +avatarUrl + '"/>');
	blockedElt.attr("title", getParticipantTooltip(blockedParticipant));
	$(".lot-participant-drag-hint", dropTarget).hide();
	var elt = blockedElt.appendTo(dropTarget).click(function(){
		removeBlock(participant, blockedParticipant);
	    });
	if (!isInit) {
	    elt.hide().fadeIn('slow');
	}
    }


    function init() {
	$('#participants_more').click(moreParticipants);
	$('#participants_less').click(lessParticipants);
	var cnt = participantCount() + 1;
	$('#participant_table tr:lt('+cnt+')').show();

	$(".participant_avatar_drag").draggable({helper: 'clone'});
	$(".participant_blocks").droppable({
		accept: ".participant_avatar_drag",
		    activeClass: 'exclude_active',
		    hoverClass: 'exclude_hover',
		    drop: function(ev, ui) {
		    var blockedParticipant = elementToParticipantNr(ui.draggable);
		    var participant = elementToParticipantNr(this);
		    addBlock(participant, blockedParticipant, false);
		}
	    });
	for (var p = 0; ; p++) {
	    var empty = true;
	    for (var q = 0; ; q++) {
		if (p != q) {
		    var cb = getBlockCheckbox(p, q);
		    if (cb.length == 1) {
			empty = false;
			if (isBlocked(p, q)) {
			    addBlock(p, q, true);
			}
		    }
		    else {
			break;
		    }
		}
	    }
	    if (empty) {
		break;
	    }
	}
	$(".lot-participant-email input").change(function() {
		var rowNr = $(this).closest("tr").attr("id").replace("participant_row_", "");
		var url = getParticipantAvatarUrl(rowNr);
		$("img.lot-participant-avatar-"+rowNr, $("#participant_table")).attr("src", url);
		updateParticipantTooltip(rowNr);
	    });
	$(".lot-participant-name input").change(function() {
		var rowNr = $(this).closest("tr").attr("id").replace("participant_row_", "");
		updateParticipantTooltip(rowNr);
	    });
	updateMoreLessButtons();
    }

    init();
    });
}


function lotMessages() {
    $(function() {
	var messages = $("#lot-messages");
	var form = $(".lot-message-form");
	
	function formAttach(parentPk, msgForm, opts) {
	    // Elements
	    var textarea = $("textarea", msgForm);

	    // Hookup label-for
	    $("input[name='impersonate']", msgForm).each(function(i, elt) {
		var $elt = $(elt);
		var eid = "imp-" + parentPk + "-" +  $elt.val();
		$elt.attr("id", eid);
		$elt.next("label").attr("for", eid);
	    });
	    // Cancel button
	    if (opts.cancel) {
		$(".lot-message-action-cancel", msgForm)
		    .show().click(function() {
			msgForm.slideUp();
		    });
	    }
	    // Form data
	    function formData() {
		var data = { comment: $.trim(textarea.val()) };
		if (data.comment) {
		    var r = $("input[type=radio][name=impersonate]:checked", 
			      msgForm);
		    data[r.data("masquerade")] = r.val();
		    data.parent = parentPk;
		    return data;
		}
		return null;
	    }

	    // Post
	    $(".lot-message-action-post", msgForm).click(function() {
		var data = formData();
		if (data !== null) {
		    $.ajax({ url: document.location.href,
			     data: data,
			     type: "POST",
			     complete: function() {
			     },
			     success: function(resp) {
				 textarea.val("");
				 var e = $(resp.html);
				 e.hide();
				 if (parentPk) {
				     msgForm.slideUp("fast", function() {
					 e.insertAfter($("#lot-message-"+parentPk));
					 e.slideDown();
				     });
				 } else {
				     e.prependTo(messages);
				     e.slideDown();
				 }
			     }
			   });
		}
		return false;
	    });
	}

	formAttach("", form, { cancel: false });

	$(".lot-message-reply").live("click", function() {
	    var msgDiv = $(this).closest(".lot-message-outer");
	    var rform = $(".lot-message-form", msgDiv);
	    if (! rform.length) {
		var rform = $(form).clone();
		rform.hide();
		formAttach(msgDiv.data("pk"), rform, { cancel: true });
		rform.appendTo(msgDiv);
	    }
	    rform.slideDown();
	    return false;
	});
    });
}

function lotLandingPage() {
$(function() {

var e = $("div.lot-carousel-view");
$(".lot-features dt").each(function() {
var car = $("#lot-carousel .lot-carousel-view");
var dt = $(this);
var dd = dt.next();
var f =$('<div class="lot-feature"><h3>'+dt.html()+'</h3><p>'+dd.html()+'</p></div>');
f.appendTo(e);
f.data({dt:dt});
dd.remove();
dt.mouseleave(function() {
car.trigger("play", true);
});
dt.bind("mouseenter click", function() 
{
$(".lot-features dt").removeClass("lot-hover");
car.trigger("play", true);
car.trigger("slideTo", [f, 0]);
car.trigger("pause", true);
});

});

  $("#lot-carousel .lot-carousel-view").carouFredSel({auto:true,
circular: false,
direction: "up",
height: 160,
auto: { pauseDuration: 1000, duration: .2 },



scroll: {items: 1, pauseOnHover: true,
onBefore: function(oldItems, newItems, newSizes, duration) {
oldItems.data("dt").removeClass("lot-hover");
newItems.data("dt").addClass("lot-hover");
}

},
 prev : {   
        button  : "#foo2_prev",
        key     : "left"
    },
    next : {
        button  : "#foo2_next",
        key     : "right"
    },
//    pagination  : "#foo2_pag"
 });
});

}

