﻿var Donation = {

	programSections: [],
	amountSections: [],
	programLinks: [],
	currentProgram: 0,

	init: function () {
		Donation.initializeProperties();
		$$('.program fieldset').invoke('observe', 'click', Donation.onInputChanged);
		Donation.highlightInitialLabels();
		this.urlHash = window.location.hash.replace('#', '') || false;
		
		this.programLinks = $$('.program_nav a');
		this.programLinks.invoke('observe', 'click', Donation.onProgramChanged);
		if (this.urlHash) {
			for (var i = 0; i < this.programLinks.length; i++) {
				if (this.programLinks[i].href.indexOf(this.urlHash) != -1) {
					// deregister swf movie if available, to stop it from playing on tab switch
					if (Donation.programSections[Donation.currentProgram].select('#support_swf_video').length > 0) {
						$('support_swf_video').innerHTML = '';
						delete swf;
					}
					Donation.updateSelectedTab(i, this.programLinks[i]);
				}
			}
		}

	},


	initializeProperties: function () {
		this.programSections = $$('.program');
		this.programLinks = $$('.program_nav a');
		this.num = 0;
	},

	/*highlightInitalElements: function() {
	this.highlightProgram(0);
	this.highlightElement(Donation.programLinks[0]);
	this.highlightElement([
	Donation.programLinks[0],
	$$('.company_benefits div:first-child'),
	$$('.member_benefits div:first-child')
	]);
	},*/

	highlightInitialLabels: function () {
		var checkedInputs = $$("input[type='radio']").select(function (el) { return el.checked });
		checkedInputs.each(function (input) {
			var label = Donation.getLabel(input);
			Donation.highlightElement(label);
		});
	},

	onProgramChanged: function (event) {
		event.stop();
		var linkHash = event.findElement('a').hash;

		$$("input[type='radio']").each(function (elem) {
			elem.checked = false;
		});

		$$('label', 'div.company_benefits div', 'div.member_benefits div').each(function (elem) {
			elem.removeClassName('hi').addClassName("off");
		});
		$$('input.customAmount').each(function (elem) {
			elem.value = '';
		});
		$$('.current_amount_text').each(function (elem) {
			elem.innerHTML = '';
		});
		$$('.your_gift_text').each(function (elem) {
			elem.innerHTML = '';
		});
		
		// deregister swf movie if available, to stop it from playing on tab switch
		if (Donation.programSections[Donation.currentProgram].select('#support_swf_video').length > 0) {
			$('support_swf_video').innerHTML = '';
			delete swf;
		}

		var link = Event.element(event);
		window.location.hash = link.hash;
		if (link.tagName.toLowerCase() != 'a') return;

		var index = 0;
		if (this.num > 0) {
			index = num;
		} else {
			index = Donation.programLinks.indexOf(link);
		}

		Donation.updateSelectedTab(index, link);
	},

	onInputChanged: function (event) {
		//Update this for all OtherAmountTxt
		var elCustomAmountInputs = $$('input.customAmount');
		for (var i = 0, len = elCustomAmountInputs.size(); i < len; i++) {
			elCustomAmountInputs[i].value = '';
		}
		var el = Event.element(event);
		if (el.tagName.toLowerCase() != 'input') return;
		var index = $(el.parentNode).select('input').indexOf(el);
		Donation.highlightAmountSections(index);
		Donation.highlightElement(Donation.getLabel(el));
		Donation.updateAmount(el);
	},

	highlightAmountSections: function (index) {
		var currentDiv = this.programSections[this.currentProgram];
		this.highlightElement([
					currentDiv.select('.company_benefits div')[index],
					currentDiv.select('.member_benefits div')[index]
			]);
	},

	updateText: function (selector, text) { // for changing donation program and amounts
		selector = $$(selector);
		selector.each(function (el) {
			el.innerHTML = text;
		})
	},

	highlightElement: function (el) {
		if (Object.isArray(el)) {
			el.each(Donation.highlightElement);
		}
		else {
			var tag = el.tagName.toLowerCase();
			$(el.parentNode).select(tag + '.hi').invoke('removeClassName', 'hi').invoke('addClassName', 'off');
			el.addClassName('hi').removeClassName('off');
		};
	},

	highlightProgramSections: function (sections, index) {
		sections.each(function (section) {
			Donation.highlightElement(section[index]);
		});
	},

	updateAmount: function (input) {
		if (!input) {
			var input = this.programSections[this.currentProgram].select("input[type='radio']")
			.select(function (el) { return el.checked })[0];
		}

		var amt = 0;
		if (input) {
			var amt = this.getLabel(input).innerHTML;
		}
		this.updateText('.current_amount_text', amt);
	},

	highlightProgram: function (index) {
		this.programSections.invoke('removeClassName', 'hi');
		this.programSections[index].addClassName('hi');
	},

	getLabel: function (el) {
		var label = $$('label[for="' + el.id + '"]')[0];
		return label;
	},

	updateSelectedTab: function (index, link) {
		Donation.highlightProgram(index);
		Donation.highlightElement(Donation.programLinks[index]);
		Donation.updateText('.current_program_text', link.innerHTML);

		var el = $$("#program_" + (index + 1) + "_amt_0").first();
		el.checked = true;
		Donation.currentProgram = index;
		Donation.highlightAmountSections(index);
		Donation.highlightElement(Donation.getLabel(el));
		Donation.updateAmount();

		// re-register swf movie if there was one
		if (Donation.programSections[Donation.currentProgram].select('#support_swf_video').length > 0) {
			var swf = new SWFObject("https://www.seattleopera.org/support/video-music-player-donate-page.swf", "Support Seattle Opera", "424", "265", "8", "#000000");
			swf.write("support_swf_video");
		}

		var e = $$("div#ProgramWrapperDiv" + index + " div.company_benefits div.hi");
		var programWrapper = $$("div#ProgramWrapperDiv" + index + " fieldset input");

		var el = programWrapper[0];
		if (el.tagName.toLowerCase() != 'input') return;
		var index = $(el.parentNode).select('input').indexOf(el);
		Donation.highlightAmountSections(index);
		Donation.highlightElement(Donation.getLabel(el));
		Donation.updateAmount(el);
	}

}
document.observe('dom:loaded', Donation.init);



//Show custom amount text on field focus


var ProcessDonationForm = {
    initialize: function () {
        this.inputsCustomAmt = $$('input.customAmount');
        this.length = this.inputsCustomAmt.size();
        var boundInputBlur = this.__InputBlur.bindAsEventListener(this);
        this.inputsCustomAmt.invoke('observe', 'blur', boundInputBlur);
    },
    __InputBlur: function (e) {
        var el = e.findElement('input');
        for (var i = 0; i < this.length; i++) {
            if (this.inputsCustomAmt[i] == el) {
                this.updateCustom(i);
                break;
            }
        }
    },
    updateCustom: function (index) {
        //        this.value = commaSplit(this.value);
        var customAmt = $('OtherAmountTxt' + index).value;
        var displayAmt = $$('.current_amount_text');

        if (isNaN(customAmt) || customAmt == "") {
            $$('input.customAmount').each(function (elem) {
                elem.value = '';
            });
            $$('.current_amount_text').each(function (elem) {
                elem.innerHTML = '';
            });
            $$('.your_gift_text').each(function (elem) {
                elem.innerHTML = '';
            });
        }
        else {
            var amt = '$' + commaSplit(customAmt);
            displayAmt.invoke('update', amt);
            //console.log("updateAmount: " + $$('.your_gift_text').innerHTML);
            $$('.your_gift_text').each(function (el) {
                el.innerHTML = "of " + amt;
            });
            //console.log("updateAmount: " + $$('.your_gift_text').innerHTML);
        }

        var contentDivs = $$('div#ProgramWrapperDiv' + index + ' div.company_benefits div');
        contentDivs.invoke('removeClassName', 'hi');
        contentDivs.invoke('addClassName', 'off');
        contentDivs.last().addClassName('hi').removeClassName('off');

        var memberDivs = $$('div#ProgramWrapperDiv' + index + ' div.member_benefits div');
        memberDivs.invoke('removeClassName', 'hi');
        memberDivs.invoke('addClassName', 'off');
        memberDivs.last().addClassName('hi').removeClassName('off');

        $$('label').each(function (elem) {
            elem.removeClassName('hi');
        });

        $$("input[type='radio']").each(function (elem) {
            elem.checked = false;
        });
    }
}
document.observe('dom:loaded', function () {
    ProcessDonationForm.initialize();
    //    $$('input[type=radio]').each(function(elem) {
    //        elem.checked = false;
    //    });
    //    $$('label', 'div.company_benefits div', 'div.member_benefits div').each(function(elem) {
    //        elem.removeClassName('hi');
    //    });
    //    $$('input.customAmount').each(function(elem) {
    //        elem.value = '';
    //    });
    //    $$('.your_gift_text').each(function(elem) {
    //        elem.innerHTML = '';
    //    });
});


//Calculate Monthly Payments

function calculate_click() {
    new Ajax.Updater('payments',
                      virtualRoot + '/_ajax/donations/MonthlyPayments.aspx' +
                        '?donation=' + $F($("donationTxt")) +
                        '&months=' + $("PaymentInstallments").value +
                        '&date=' + ($("InstallmentOn15th").checked ? 15 : 1)
                    );
};

window.onload = function () {
    if (!$("monthlyAmount"))
        return false;

    $("monthlyAmount").value = "";
    $("calculate").onclick = calculate_click;
};


//Add formatting for numbers that need comma separation

function commaSplit(srcNumber) {
    var txtNumber = '' + srcNumber;
    if (isNaN(txtNumber) || txtNumber == "") {
        //TODO: Generic error handling
    }
    else {
        var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
        var arrNumber = txtNumber.split('.');
        arrNumber[0] += '.';
        do {
            arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');
        } while (rxSplit.test(arrNumber[0]));
        if (arrNumber.length > 1) {
            return arrNumber.join('');
        }
        else {
            return arrNumber[0].split('.')[0];
        }
    }
}


