var textAreas = [];
var labels = [];
var currentVisisble = [];
$(document).ready(function() {

    var object = $('.tabbedGroupHeading');
    for (var objCount = 0; objCount < object.length; objCount++) {
        textAreas[objCount] = new Array();
        labels[objCount] = new Array();
        //finds the section heading and gets it's tr
        tr = $(object[objCount]).closest('tr').get();
        var foundAll = false;
        //loops through and finds all the textareas below it, capturing the textarea id and the label text
        while (!foundAll) {
            tr = $(tr[0]).next('tr');
            if (tr.length == 0) {
                foundAll = true;
                break;
            }
            var textArea = $(tr[0]).find('textarea');
            var label = $(tr[0]).find('label');
            if (textArea.length > 0 && label.length > 0) {
                textAreas[objCount].push(textArea[0].id);
                labels[objCount].push(label[0].innerHTML);
            }
            else {
                foundAll = true;
                break;
            }
        }
        //loops through again and hides all the rows except the first one
        for (var i = 1; i < textAreas[objCount].length; i++) {
            var element = $('#' + textAreas[objCount][i]).closest('tr').get()[0];
            $(element).addClass("hide"); 
        }



        currentVisisble[objCount] = textAreas[objCount][0];
        //gets the first tr again and injects the ul for the questions in it
        tr = $(object[objCount]).closest('tr').get();
        var ul = '<tr><td><ul id="ulTabbedNavigation">';
        for (var i = 0; i < labels[objCount].length; i++) {
            ul += '<li class="tabGroup"><a href="#' + textAreas[objCount][i] + '">' + labels[objCount][i] + '</a></li>';
        }
        ul += '</ul></td></tr>';
        //injects the new ul as the first row before the first text area
        $(tr).after(ul);

        //loops through and adds the 
        for (i = 0; i < textAreas[objCount].length; i++) {
            $("a[href$='" + textAreas[objCount][i] + "']").click(function(event) {
                swapFocusedTab(event);
            });
        }
    }
});

function swapFocusedTab(event) {
    //grabs the href of the target and finds the name of the control
    var href = event.target.href;
    href = href.substring(href.lastIndexOf('#') + 1)
    var currentSection = 0;
    if(textAreas.length > 1)
    {
        for(var i = 0; i<textAreas.length; i++)
        {
            for (var j = 0; j < textAreas[i].length;  j++) {
                if (textAreas[i][j] == href) {
                    currentSection = i;
                }
            }
        }
    }
    
    //quick check to stop the user hiding itself
    if (href != currentVisisble[currentSection]) {
        //gets the tr for the new item and shows it
        var tr = $('#' + href).closest('tr').get();
        //$(tr[0]).show();
        $(tr[0]).removeClass('hide');
        //then hides the old one
        var currentEl = $('#' + currentVisisble[currentSection]).closest('tr').get()[0];
        //$(currentEl).hide();
        $(currentEl).addClass('hide');
        //find the which section we are in
        
        currentVisisble[currentSection] = href;
    }
    //stops it from jumping to the # link
    event.preventDefault();
    
    
}

function getTabbedElements (el, objects) {
    
    var children = $(el).find("textarea");
    
    for (var i = 0; i < children.length; i++) {
        alert(children[i].tagName);
    }
}

function nextSiblingElement(element) {
	do element = element.nextSibling;
	while (element && element.nodeType != 1);
	return element;
}
function previousSiblingElement(element) {
	do element = element.previousSibling;
	while (element && element.nodeType != 1);
	return element;
}

function ValidateNumberTotal(totalBoxId) 
{
    var totalBox = document.getElementById(totalBoxId);

    if (totalBox == null) {
        alert("Cannot add number total. Ensure the number total is not read only.");
    }
}

function SetUpNumberTotal(totalBoxId)
{
    var totalBox = document.getElementById(totalBoxId);
 
	var currentRow = FindParentRow(totalBox);
    if(!currentRow) return;
    
    var total = 0;
    
    do
    {
    	var numberBox = FindNumberBox(currentRow);
        if(!numberBox) break;
        if(!numberBox.className) continue;
        if(numberBox.className.indexOf('formInputNumber') == -1) continue;
        if(numberBox.className.indexOf('formInputNumberTotal') > -1)
        {
            if ($(numberBox).parent().html().indexOf('ro-') == -1) 
            {
                $(numberBox).hide();
                $(numberBox).parent().append("<span id='ro-" + numberBox.id + "'>0</span>");
            }
        }
        else
        {
            if (numberBox.onblur == null) {
                numberBox.onblur = function() { CalculateTotal(totalBox) };
            }
		}
    }
    while(currentRow = previousSiblingElement(currentRow))

    totalBox.value = total;
    CalculateTotal(totalBox);
}

function CalculateTotal(totalBox)
{
    var currentRow = FindParentRow(totalBox);
    if(!currentRow) return;

    var total = 0;
    if (typeof (CalculateCustomTotal) === 'function') {
        total = CalculateCustomTotal();
    }
    else {
        while (currentRow = previousSiblingElement(currentRow)) {
            var numberBox = FindNumberBox(currentRow);
            if (!numberBox) break;
            if (!numberBox.className) continue;
            if (numberBox.className.indexOf('formInputNumber') == -1) continue;
            if (numberBox.className.indexOf('formInputNumberTotal') > -1) break;
            var val = numberBox.value;
            if (isNaN(val)) continue;
            total += (val * 1);
        }
    }
    totalBox.value = total;
    
    $("#ro-" + totalBox.id).html(total);
    
    if(typeof(updateGiftAid) === 'function') {
		updateGiftAid();
	}
}


function FindParentRow(obj)
{
	var result = obj;
	while(result = result.parentNode)
	{
		if(result.tagName == 'TR') return result;		
	}
	return null;
}

function FindNumberBox(obj)
{
	var result = null;
	for(var i=0; i<obj.childNodes.length; i++)
	{
    	var child = obj.childNodes[i];
    	if(child.tagName == 'INPUT')
		{
    		result = child;
			break;
		}
		else
		{
    		result = FindNumberBox(child);
			if(result) break;
		}
	}
	return result;
}

jQuery.fn.maxLenCounter = function(set_max) {
    jQuery(this).each(function() {
        var textarea = jQuery(this).is('textarea');
        var max = set_max ? set_max : jQuery(this).attr('maxlength');
        if (!max || max == 2147483647) { return; } //IE6 fix
        var val = textarea ? jQuery(this).val() : jQuery(this).attr('value');
        var left = max - (val ? val.length : 0);
        jQuery(this).after("<span class='maxlencounter'>" + left.toString() + "</span>");
        var c = jQuery(this).next(".maxlencounter");
        c.css("padding", "0 0 0 4px;");
        c.css("font-size", "85%");
        c.css("color", "#666");
        c.width(40);
        jQuery(this).keyup(function(e) {
            var val = textarea ? jQuery(this).val() : jQuery(this).attr('value');
            var left = max - (val ? val.length : 0);
            if (left < 0) {
                cutval = val.substr(0, max);
                textarea ? jQuery(this).val(cutval) : jQuery(this).attr('value', val);
                left = 0;
            }
            if (left == 0) {
                c.css("color", "#F00");
            }
            else {
                c.css("color", "#666");
            }
            jQuery(this).next(".maxlencounter").text(left.toString());
            return this;
        });
    });
    return this;
}

function disableEnterKey(e) {
     var key;      
     if(window.event)
          key = window.event.keyCode;
     else
         key = e.which;
         
     return (key != 13);
}

function keyPressReturnCancelBubble(event) {
    var intKeyCode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
    if (intKeyCode == 13) {
        event.cancelBubble = true;
    }
    return true;
}

