var loginEventManager;
$(function () {
    $("#id_q").labelify({ labelledClass: "searchHighlight" });
    $("#id_qa").labelify({ labelledClass: "searchHighlight" });
    $('#join-team-explore #id_email').labelify({ labelledClass: "searchHighlight", text: "label" });

    $("#topbar form a").click(function () { $(this).parent().submit(); return false; });
    $("form#search_again a").click(function () { $(this).parent().submit(); return false; });
    $("#join-team-explore img").click(function () { $(this).parent().submit(); return false; });

    $(".modalbutton").click(function () {
        openModal($(this).attr('href'));
        return false;
    });

    if (showScrollbars()) {
        $('.scroll').jScrollPane({ 'showArrows': true, 'reinitialiseOnImageLoad': true });
    }

    tagIndex = 0;
    tags = $("#taglines").children();
    tagMax = tags.length;
    tagA = [];
    tagInterval = 0;

    if (tagMax > 1) {
        $(tags).each(function () {
            var c = $(this).attr('class').split('_');
            d = 10000;
            if (parseInt(c[1], 10) > 1) {
                d = parseInt(c[1], 10);
            }
            tagA.push({ tag: $(this).text(), duration: d });
        });
        clearInterval(tagInterval);
        tagInterval = setInterval(swapTag, tagA[tagIndex].duration);
    }

    $('a.print').click(function () {
        window.print();
    });

    $("a.jump_link, .jump_links a").click(function () {
        var tar = $(this).attr("href");
        $.scrollTo(tar, 800, { easing: 'easeInOutQuad' });
        return false;
    });

    //promo modules
    if ($('.enews_smart').length) {
        $('.enews_smart input[type="text"]').labelify({ labelledClass: "labelHighlight" });
        $('.enews_smart input[type="submit"]').click(function (e) {
            var t = $(this).parent().find('.text');
            if ($(t).val() != $(t).attr('title')) {
                openModal($(this).parent().attr('action') + '?' + $(this).parent().serialize());
            }
            e.preventDefault();
            e.stopImmediatePropagation();
            return false;
        });
    }

    loginEventManager = new LoginEventManager();

    loginEventManager.addListener("login", function() { 
        $('#join-team-explore').parent().hide();
	});

});

function albumView(target) {
	
	var target = $(target);
	var json_target = '/' + target.attr('ref') + '/' + target.attr('rel') + '.json';
	var json = $.getJSON(json_target, {}, function(data){
		$("#col_" + data.collection).bind('mousemove', function(e){
			var x = e.pageX - $(this).offset().left;
			var modW = 198/(data.photos+1);
			var index = Math.floor(x / modW);
			$(this).css("background-position", "0px " + -($(this).height()*index) + "px");
		});
		$("#col_" + data.collection).bind('mouseout', function(e){
		   $(this).css("background-position", "0px 0px"); 
		});
		
		$("#col_" + data.collection).bind('click', function(e){
			var x = e.pageX - $(this).offset().left;
			var modW = 198/(data.photos+1);
			var index = Math.floor(x / modW) - 1;
			var location = window = target.attr("href");
			if(index != -1){
				location += "/#"+index;
			}
			window.location = location;
			e.preventDefault();
			e.stopImmediatePropagation();
			
		});
		
	});
}


function openModal(url)
{
	$.modal('<iframe class="modal" name="modal-overlay" scrolling="no" src="' + url + '" frameborder="0">',
	{
		overlay: 80,
		overlayClose: true
	});	
}

function closeModal()
{
  $.modal.close();
}

function setLoggedInAs(userName) {
    $('.user-name').html(userName);
    $('#login').hide();
    $('#logout').show();
}

function showScrollbars()
{
	if(!$.browser.msie || ($.browser.msie && parseInt($.browser.version) > 7)){
		return true;
	}
	return false;
}

function swapTag()
{
	clearInterval(tagInterval);
	$('#tagline').animate({'opacity':0.0},function(){
		if(tagIndex<tagMax){
			tagIndex++;
		}
		if(tagIndex == tagMax){
			tagIndex=0;
		}
		$('#tagline').text(tagA[tagIndex].tag);
		$('#tagline').animate({'opacity':1.0});
		tagInterval = setInterval(swapTag,tagA[tagIndex].duration);
	});
}

function EventTarget() {
    this._listeners = {};
}

EventTarget.prototype = {

    constructor: EventTarget,

    z: function() { alert(this._listeners); },

    addListener: function (type, listener) {
        if (typeof this._listeners[type] == "undefined") {
            this._listeners[type] = [];
        }

        this._listeners[type].push(listener);
    },

    fire: function (event) {
        if (typeof event == "string") {
            event = { type: event };
        }
        if (!event.target) {
            event.target = this;
        }

        if (!event.type) {  //falsy
            throw new Error("Event object missing 'type' property.");
        }

        if (this._listeners[event.type] instanceof Array) {
            var listeners = this._listeners[event.type];
            for (var i = 0, len = listeners.length; i < len; i++) {
                listeners[i].call(this, event);
            }
        }
    },

    removeListener: function (type, listener) {
        if (this._listeners[type] instanceof Array) {
            var listeners = this._listeners[type];
            for (var i = 0, len = listeners.length; i < len; i++) {
                if (listeners[i] === listener) {
                    listeners.splice(i, 1);
                    break;
                }
            }
        }
    }
};

function LoginEventManager() {
    EventTarget.call(this);
}

LoginEventManager.prototype = new EventTarget();
LoginEventManager.prototype.constructor = LoginEventManager();
LoginEventManager.prototype.login = function () {
    this.fire("login");
};
