/*delegates are the win*/
function Delegate(f)
{
	this.func = f;
}
Delegate.prototype.func = function(){}
Delegate.create = function(obj, func)
{
	var f = function()
	{
		var target = arguments.callee.target;
		var func = arguments.callee.func;
		if(func && target)
		    return func.apply(target, arguments);
		return null;
	};

	f.target = obj;
	f.func = func;

	return f;
}

Delegate.prototype.createDelegate = function(obj)
{
	return create(obj, func);
}

String.prototype.toUSD = function() {
    var num = this.replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

String.prototype.isEmail = function() {
    var regex = new RegExp("^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$");
    return regex.test(this);
}

var formatUSNumber = function (input) {
    var unformattedNumber = input.replace(/\D/g, "");
    var formattedNumber = unformattedNumber;

    try {
        //555
        if (unformattedNumber.length >= 3) {
            formattedNumber = unformattedNumber.substring(0, 3) + "-";
        }
        //555-5??
        if (unformattedNumber.length > 3 && unformattedNumber.length < 6)
            formattedNumber += unformattedNumber.substring(3, unformattedNumber.length);
        //555-555-5???
        if (unformattedNumber.length >= 6) {
            formattedNumber += unformattedNumber.substring(3, 6);
            formattedNumber += "-" + unformattedNumber.substring(6, unformattedNumber.length);
        }
    }
    catch (err) {
        formattedNumber = input;
        //alert("United States phone numbers must have exactly ten digits.");
        return this;
    }
    return formattedNumber;
}

var restrictToNumbersInput = function(e) {
    if (e) {
        var num = /[0-9]+/;
        var allowedKeyCodes = [8, 9, 35, 36, 46, 37, 38, 39, 40];
        var keyPressed = (e.charCode) ? String.fromCharCode(e.charCode) : String.fromCharCode(e.keyCode);
        if (keyPressed)
            keyPressed = keyPressed.toLowerCase();
        if ((e.ctrlKey || e.metaKey) && keyPressed == "v") {
            //could be pasting
            return true;
        }
        else
            if (!num.test(keyPressed) && allowedKeyCodes.indexOf(e.keyCode) < 0) {
            return false;
        }
        else
            return true;
    }
    else {
        console.log("no event");
    }
}

var Flux = Class.create();

//requires Delegate class
Flux.ImageSwitcher = Class.create({
    containerId: null,
    divImageClassName: 'switch_image',
    backgrounds: new Array(),
    tagLines: new Array(),
    tagLineWidths: new Array(),
    currentIndex: -1,
    interval: 3,
    isActive: false,
    periodicalExecuter: null,
    initialize: function(containerId, divImageClassName, intervalInSeconds)
    {
        this.containerId = containerId;
        this.divImageClassName = divImageClassName;
        if (intervalInSeconds)
            this.interval = intervalInSeconds;
        this.capture();
    },
    capture: function(){
        this.backgrounds = $$('#'+this.containerId+' div.' + this.divImageClassName);
        for (var i = 0; i < this.backgrounds.length; i++) {
            var children = this.backgrounds[i].childElements();
            for (var c = 0; c < children.length; c++) {
                if (children[c].hasClassName('tagline'))
                {
                    this.tagLines[i] = children[c];
                    this.tagLineWidths[i] = children[c].getWidth();
                    children[c].hide();
                    break;
                }
            }
        }
    },
    switchToDefault: function()
    {
        var random = Math.floor(Math.random()*(this.backgrounds.length-1));
        this.switchTo(random);
    },
    switchTo: function(imageIndex) {
        if (this.currentIndex == imageIndex && this.currentIndex != -1)
            return;
        if (this.currentIndex == -1)
            this.currentIndex = this.backgrounds.length-1;
        if (this.backgrounds.length == 0)
            this.capture();
        //place the next on top z-index
        var currentImage = $(this.backgrounds[this.currentIndex]);
        var currentTagline = $(this.tagLines[this.currentIndex]);
        if (imageIndex >= this.backgrounds.length)
            this.currentIndex = 0;
        else
            this.currentIndex = imageIndex;
        var nextImage = this.backgrounds[this.currentIndex];
        var container = $(this.containerId);
        if (nextImage && currentImage && container)
        {
            //display:none
            currentImage.style.zIndex = 100;
            nextImage.style.zIndex = 200;
            nextImage.style.width = "0%";
            nextImage.show();
            new Effect.Morph(nextImage, {style: 'width:100%;', afterFinish: Delegate.create(currentImage, currentImage.hide)});

            if (currentTagline)
            {
                //currentTagline.style.zIndex = 60;
                currentTagline.slideUp({duration:0.8, afterFinish: Delegate.create(this, this.showCurrentTagline)});
            }
            else
            {
                this.showCurrentTagline();
            }
        }
    },
    switchNext: function() {
        var nextIndex = this.currentIndex + 1;
        if (nextIndex >= this.backgrounds.length)
            nextIndex = 0;
        //console.log('switching to ' + this.currentIndex + '; ' + nextIndex + ' of ' + this.backgrounds.length);
        this.switchTo(nextIndex);
    },
    start: function(intervalInSeconds)
    {
        if (intervalInSeconds == null)
            intervalInSeconds = this.interval;
        this.stop();
        this.periodicalExecuter = new PeriodicalExecuter(Delegate.create(this, this.switchNext), intervalInSeconds);
        this.switchNext();
    },
    stop: function()
    {
        if (this.periodicalExecuter)
            this.periodicalExecuter.stop();
    },
    showCurrentTagline: function()
    {
        var nextTagline = this.tagLines[this.currentIndex];
        if (nextTagline)
        {
            //nextTagline.style.zIndex = 300;
            nextTagline.slideDown({duration:1.2, delay: 0.3});
        }
    }
});

Flux.BackgroundImageObject = Class.create({
    url: "",
    projectId: 0,
    initialize: function(url, projectId){
        if (projectId)
            this.projectId = projectId;
        this.url = url;
    }
})

Flux.TagLineObject = Class.create({
    text: "",
    x: 0,
    y: 0,
    height: 0,
    width: 0,
    entersFrom: "",
    initialize: function(text, x, y, width, height, entersFrom){
        this.text = text;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.entersFrom = entersFrom;
    }
})

var HFF = function() {};
HFF.ContactForm = Class.create({
    form: null,
	errorContainer: null,
	nameField: null,
	emailField: null,
	phoneField: null,
	messageField: null,
	initialize: function(formId, errorContainerId)
	{
		this.form = $(formId);
		this.errorContainer = $(errorContainerId);
		this.capture();
		this.phoneField.observe('keyup', Delegate.create(this, this.onPhoneKeyup));
	},
	capture: function(){
		var children = this.form.childElements();
		for (var i = 0; i < children.length; i++)
		{
			var child = children[i];
			switch(child.getAttribute('name')) {
				case 'name':
					this.nameField = child;
					break;
				case 'email':
					this.emailField = child;
					break;
				case 'phone_number':
					this.phoneField = child;
					break;
				case 'message':
					this.messageField = child;
					break;
			}
		}
	},
	validate: function() 
	{
		if (this.nameField.value.replace(/\s+/g, '') == '')
		{
			this.nameField.shake();
			this.showError('Please provide your name.');
			return false;
		}
		
		if (!this.emailField.value.isEmail() && this.emailField.value != '')
		{
			this.emailField.shake();
			this.showError('Please provide a valid email address.');
			return false;
		}
		
		if (this.emailField.value == '' && (this.phoneField.value == '' || this.phoneField.value.length < 12))
		{
			this.phoneField.shake();
			this.showError('Please provide a valid phone number.');
			return false;
		}
		
		if (this.messageField.value.replace(/\s+/g, '') == '')
		{
			this.messageField.shake();
			this.showError('Please provide a message.');
			return false;
		}
		
		this.clearErrors();
		return true;
	},
	clearErrors: function() 
	{
		this.errorContainer.innerHTML = '';
		this.errorContainer.hide();
	},
	showError: function(errorMessage)
	{
		if (errorMessage != '')
		{
			this.errorContainer.innerHTML = '<div class="error">' + errorMessage + '</div>';
			this.errorContainer.slideDown();
		}
	},
	onPhoneKeyup: function(e) {
		this.phoneField.value = formatUSNumber(this.phoneField.value);
	}
});
