// Mailing list
function MailingList(x)
{
	this.c = $(x.container);
	if (this.c.length == 0) return;
	c = this.c;
	
	this.inputs = this.c.find("input[type=text]");	
	this.form = this.c.find("form");

	this.inputs.focus(function() {
		if ($(this)[0].defaultValue == $(this).val()) {
			$(this).val('');
		}
	});
	
	this.inputs.blur(function() {
		if (!$(this).val()) {
			$(this).val($(this)[0].defaultValue);			
		}
	});
	
	var email = this.c.find("input[name=email]");
	var zip = this.c.find("input[name=zip]");	
	var mobile = this.c.find("input[name=mobile]");	
    
	var country = this.c.find("select[name=country]");
    country.change(function(){
        if($(this).val() == 'US') {
            zip.altRemoveClass('hidden');
        } else {
            if(!zip.hasClass('hidden')){
                zip.altAddClass('hidden');
            }
        }
    });
    
	this.form.submit(function(event) {

        var errors = [];
        
        // Find errors
        if (email.val() == '' || email[0].defaultValue == email.val()) { errors.push('Please enter a valid email address'); }
        if (country.val() == '') { errors.push('Please select a country'); }
        if (country.val() == 'US' && (zip.val() == '' || zip[0].defaultValue == zip.val())) { errors.push('Please enter your zip code'); }
        
        // return errors
        if(errors.length > 0) {
            alert(errors[0]);
            return false;
        
        // or submit
        } else {
            
            // set zip back to ''
            if(zip.val() == '' || zip[0].defaultValue == zip.val()) { zip.val(''); }
            
            $.post('/poly/api/mailinglist/add',{"email":email.val(),"country":country.val(),"zip":zip.val()},function(result){
                var data = eval('('+result+')');
                if(data["errors"]) {
                    alert(data.errors[0].message);
                } else {
                    c.altAddClass('completed');
                    c.find('.container').text('Thanks for signing up! Welcome to the Playing For Change movement!');
                    
                    // Delay 5 second...
                    c.delay(3000,function(){
                        c.slideUp('fast');
                    });
                }
            });
            
            return false;
        }
        return false;
		event.preventDefault();
        event.stopPropagation();
        return false;
        
	}.bind(this));		
}

// CustomShareThis
function CustomShareThis(x)
{
	try {
		if (!SHARETHIS) return;
	} catch(e) { return; }

	$(x.link).each(function(i) {
		var share = SHARETHIS.addEntry({}, { button:false, offsetLeft:-235 });
		if (share) {
			$(this)[0].id = "sharethis_"+i;

			$(this).click(function(s, event) {
				event.preventDefault();
				event.stopPropagation();
				s.popup();								
			}.bind(this, share));
		}
	});	
	
}

// Track list
function TrackList(x)
{
	this.c = $(x.container);
	if (this.c.length == 0) return;

	var tabs = this.c.find(x.tabs || '.tabs a');
	var listing = this.c.find(x.listing || '.listing');

	tabs.each(function(i) {	
		$(this).click(function(event) {
			event.preventDefault();
			event.stopPropagation();	
			if ($(this).hasClass('selected')) {
				return;
			}
			tabs.filter('.selected').removeClass('selected');
			$(this).addClass('selected');
			
			listing.filter(function() {
				return $(this).css('display') != 'none';
			}).hide();
			listing.eq(i).fadeIn('normal');
		});
	});	
}

// Carousel
function Carousel(x)
{
	this.itemClass = x.itemClass || 'item';	
	this.items = x.items || [];
	this.config = x.config || [];
	
	this.c = $(x.container);
	if (this.c.length == 0) return;

	this.template = this.c.find(x.template || '.template');
	this.track = this.c.find(x.track || '.track');

	for (var i=0; i<this.items.length; i++)
	{
		var newItem = this.template.clone(true).appendTo(this.track);		
		this.fill(newItem, this.items[i]);
		newItem.attr('className', this.itemClass);
		newItem.show();		
	}	
	
	if (!x.unlinkItem) {
		if (this.track.find('.'+this.itemClass+' a').length) {
			this.track.find('.'+this.itemClass).click(function(event) {
				var link = $(this).find('a').eq(0);
				if (link) {
					event.preventDefault();
					event.stopPropagation();
					location.href = link.attr('href');
				}
			});
		}
	}
	
	this.captions = this.c.find(x.caption || '.caption');
	this.captions.each(function() {
		if (!$(this).html()) {
			$(this).css('display', 'none');			
		} else {
			$(this).css('display', '');
			$(this).css('visibility', 'visible');
			$(this).css('top', (0 - $(this).outerHeight()) + 'px');			
		}
	});
}

Carousel.prototype.fill = function(div, item)
{
	for (var i=0; i<this.config.length; i++)
	{
		var selector = this.config[i][0];
		var attribute = this.config[i][1];
		var data = this.config[i][2];
		div.find(selector).attr(attribute, item[data]);
	}
}

// SliderTrack

function SliderTrack(x)
{
	this.display = x.display || 4;
	this.perclick = x.perclick || this.display;
	this.offClass = x.offClass || 'Off';
	
	this.timeout = false;
	
	this.c = $(x.container);
	if (this.c.length == 0) return;
	
	this.items = this.c.find(x.item || '.item');
	this.prevButton = this.c.find(x.previous || 'a.previous');
	this.nextButton = this.c.find(x.next || 'a.next');
	this.track = this.c.find(x.track || '.track');
	this.captions = this.items.find(x.caption || '.caption')
	
	if (this.items.length == 0) return;
	
	if (x.lastClass)
	{
		for (var i=0; i<this.items.length; i++)
		{
			if ((i+1) % this.display == 0)
				this.items.eq(i).addClass(x.lastClass);
		}
	}
	
	this.width = this.items.get(0).offsetWidth;
	this.track.width(this.items.length * this.width);
	
	this.prevButton.altAddClass(this.offClass);
	if (this.items.length <= this.display)
		this.nextButton.altAddClass(this.offClass);
	
	this.first = 0;
	this.startFade();
	
	this.prevButton.click(this.prev.bind(this));
	this.nextButton.click(this.next.bind(this));	
	this.items.hover(this.showCaptions.bind(this), this.startFade.bind(this, 1000));
	
	// HACK
	this.prevButton.attr('style','');
	this.nextButton.attr('style','');
}

SliderTrack.prototype.showCaptions = function()
{
	this.cancelFade();
	this.captions.stop(true, true);
	this.captions.show();
	if (this.captions.css('background-image') == 'none') {
		this.captions.css('opacity', '0.75');
	}
}

SliderTrack.prototype.startFade = function(speed)
{
	if (this.timeout) {
		this.cancelFade();
	}

	var fn = function() {
		this.captions.fadeOut('slow');
		this.timeout = false;
	}.bind(this)
	
	this.timeout = setTimeout(fn, speed || 4000);		
}

SliderTrack.prototype.cancelFade = function()
{
	if (this.timeout) {
		clearTimeout(this.timeout);
		this.timeout = false;
	}
}

SliderTrack.prototype.prev = function(event)
{	
	event.preventDefault();
	event.stopPropagation();	
	
	if (this.prevButton.altHasClass(this.offClass)) return;
	if (this.halt) return;
	
	this.cancelFade();
	
	this.nextButton.altRemoveClass(this.offClass);
	
	this.first -= this.perclick;
	this.move(this.first * this.width);
	
	if (this.first == 0)
		this.prevButton.altAddClass(this.offClass);
}

SliderTrack.prototype.next = function(event)
{	
	event.preventDefault();
	event.stopPropagation();	
	
	if (this.nextButton.altHasClass(this.offClass)) return;
	if (this.halt) return;
	
	this.cancelFade();
	
	this.prevButton.altRemoveClass(this.offClass);

	this.first += this.perclick;
	this.move(this.first * this.width);

	if (this.first + this.display >= this.items.length)
		this.nextButton.altAddClass(this.offClass);		
}

SliderTrack.prototype.move = function(pos)
{	
	this.halt = true;
	
	this.items.parent().animate({left: -pos}, 'normal', false, function() {
		this.items.parent().css({left: -pos+'px'}); // jQuery won't take us there so force the position
		this.halt = false;
		this.showCaptions();
		this.startFade();
	}.bind(this));	
}


// UTIL
jQuery.fn.delay = function(time,func){
	this.each(function(){
		setTimeout(func,time);
	});
	
	return this;
};


jQuery.fn.extend({
	// IE6 often breaks with multiple classes on an element so we do this instead
	altToggleClass: function(c)
	{
		var r = new RegExp(c);
		var oldClass = this.attr('className');
		if (oldClass.match(r))
		{
			this.attr('className', oldClass.replace(r, ''));			
		}
		else
		{
			this.attr('className', oldClass+c);			
		}
	},
	altRemoveClass: function(c)
	{
		var r = new RegExp(c);
		var oldClass = this.attr('className');
		this.attr('className', oldClass.replace(r, ''));
	},
	altAddClass: function(c)
	{
		var oldClass = this.attr('className');
		this.attr('className', oldClass+c);			
	},
	altHasClass: function(c)
	{
		return this.attr('className').match(new RegExp(c));
	},
    findParent: function(expr)
    {
        if(!expr) return false
                
        if(this.parent().is(expr)) {
            return this.parent();
        } else if(this.parent().tagName == 'body') {
            return false;
        } else {
            return this.parent().findParent(expr);
        }
    }
	
});

// bind function
Function.prototype.bind = function(context) {
  var __method = this;
  var __arguments = [];
  for (var n = 1; n < arguments.length; n++) {
    __arguments.push(arguments[n]);    
  }
  
  return function() {
    var myargs = [];
    for (var m = 0; m < arguments.length; m++) {
      myargs.push(arguments[m]);      
    }

    return __method.apply(context, __arguments.concat(myargs));
  };
};

