/*
window.addEvent('domready', function(){

	var tips = new Tips($$('.tips'), {
		offsets: {'x': -16, 'y': 25},
		initialize:function(){
			this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);
		},
		onShow: function(toolTip) {
			this.fx.start(1);
		},
		onHide: function(toolTip) {
			this.fx.start(0);
		}
	});
});
*/

function addLoadEvent(func) {
	var oldonload = window.onload;
	if(typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

//addLoadEvent(addKeyword);
addLoadEvent(initJumpMenus);

function plateFormat(plateStr) {

	var format = "4.3"; // Default format
	if(plateStr) {
		var formatArray = plateStr.split(" ");
		var prefixStr = formatArray[0];
		var suffixStr = formatArray[1];	
		format = prefixStr.length + "." + suffixStr.length;
	}
	
	var plateFormat = document.getElementById("plateFormat");
	
	// Set the selected index	
	for(var i = 0; i < plateFormat.options.length; i++) {
		if(plateFormat.options[i].value == format) {
			plateFormat.selectedIndex = i;
			break;
		}			
	}

	// First instance
	var prefixContainer = document.getElementById("platePrefix");
	var suffixContainer = document.getElementById("plateSuffix");	
	var prefixInputs = prefixContainer.getElementsByTagName("input");
	var suffixInputs = suffixContainer.getElementsByTagName("input");
	if((prefixInputs.length + suffixInputs.length) == 0) {
		drawPlateTextboxes(format, plateStr);
	} 	
	
	plateFormat.onchange = function() {
		format = plateFormat.options[plateFormat.selectedIndex].value;
		drawPlateTextboxes(plateFormat.options[plateFormat.selectedIndex].value);
	}
}

function drawPlateTextboxes(format, plateStr) {

	// format is '.' delimited values representing
	// the number of prefix and suffix boxes 
	var formatArray = format.split(".");
	var prefixCount = formatArray[0];
	var suffixCount = formatArray[1];
	
	var prefixValues = new Array();
	var suffixValues = new Array();
	
	if(plateStr) {
		var formatArray = plateStr.split(" ");
		var prefixStr = formatArray[0];
		var suffixStr = formatArray[1];	
		format = prefixStr.length + "." + suffixStr.length;
		for(var i = 0; i < prefixStr.length; i++) {
			prefixValues[i] = prefixStr.charAt(i);						
		}
		for(var i = 0; i < suffixStr.length; i++) {
			suffixValues[i] = suffixStr.charAt(i);						
		}		
	}	

	var prefixContainer = document.getElementById("platePrefix");
	var suffixContainer = document.getElementById("plateSuffix");
	
	// TODO - save any values
	
	// Remove any existing text inputs
	var prefixInputs = prefixContainer.getElementsByTagName("input");
	var suffixInputs = suffixContainer.getElementsByTagName("input");	
	
	var prefixIds = new Array();
	var suffixIds = new Array();
	if(prefixInputs.length > 0) {
		// Get all input ids in this container
		for(var i = 0; i < prefixInputs.length; i++) {			
			prefixIds[i] = prefixInputs[i].id;
		}		
		// Remove all inputs for given id
		for(var i = 0; i < prefixIds.length; i++) {			
			removeElement(prefixIds[i]);
		}
	}
	if(suffixInputs.length > 0) {
		// Get all input ids in this container
		for(var i = 0; i < suffixInputs.length; i++) {			
			suffixIds[i] = suffixInputs[i].id;
		}		
		// Remove all inputs for given id
		for(var i = 0; i < suffixIds.length; i++) {
			removeElement(suffixIds[i]);
		}
	}		
	
	for(var i = 0; i < prefixCount; i++) {
		//var newTextbox = createTextbox("char.1." + i, 2, 1, prefixValues[i]);
		var position = i + 1;
		var newTextbox = createTextbox("prefix-" + position, 2, 1, prefixValues[i]);
		prefixContainer.appendChild(newTextbox);
	}	
	
	for(var i = 0; i < suffixCount; i++) {
		//var newTextbox = createTextbox("char.2." + i, 2, 1, suffixValues[i]);
		var position = i + 1;
		var newTextbox = createTextbox("suffix-" + position, 2, 1, suffixValues[i]);
		suffixContainer.appendChild(newTextbox);		
	}	
	
	
}

// Return input element type = text
function createTextbox(name,size,maxlength,value) {
	var widget = document.createElement("input");
	widget.setAttribute("type","text");
	widget.setAttribute("name",name);
	widget.setAttribute("id",name);
	if(value != undefined) {
		widget.setAttribute("value",value);
	}
	if(size) {
		widget.setAttribute("size",size);
	}
	if(maxlength) {
		widget.setAttribute("maxlength",maxlength);
	}	
	return widget;
}

// Return input element type = text
function createRadio(name,value,id,checked) {
	var widget = document.createElement("input");
	widget.setAttribute("type","radio");
	widget.setAttribute("name",name);
	widget.setAttribute("id",name);
	if(value != undefined) {
		widget.setAttribute("value",value);
	}
	if(id) {
		widget.setAttribute("id",id);
	}	
	if(checked) {
		widget.setAttribute("checked","checked");
	}
	return widget;
}

function createLabel(forValue,textValue) {
	var widget = document.createElement("label");
	widget.setAttribute("for",forValue);	
	text = document.createTextNode(textValue);
	widget.appendChild(text);
	return widget;
}

// Remove element
function removeElement(id) {
	var removeElement = document.getElementById(id);
	removeElement.parentNode.removeChild(removeElement);	
}

// Fee specific functions
function validateFees() {
	//alert(getTotalFeebands());
	var totalBands = getTotalFeebands();
	//alert("totalBands = " + totalBands);
	var inputs = document.getElementsByTagName("input");
	var prices = new Array();
	for(var i=0; i < inputs.length; i++) {
		
		var reMinPrice = /minPrice/;
		var reMaxPrice = /maxPrice/;
		if(reMinPrice.test(inputs[i].name + (i+1)) ) {			
			prices[inputs[i].name] = inputs[i].value;					
			
			var reDigits = /^[\d]+$/;
			if(!reDigits.test(inputs[i].value)) {
				alert("Please complete all fields with numbers ony!");
				return false;
			}			
		}
		if(reMaxPrice.test(inputs[i].name + (i+1)) ) {			
			prices[inputs[i].name] = inputs[i].value;
		}		
	} 
	//for(var i in prices) {
	//	alert('key is: ' + i + ', value is: ' + prices[i]);
	//}
	
	var errors = new Array();
	var total = totalBands;
	total++;
	for(var j=1; j < total; j++) {
		var minPrice = Number(prices["minPrice." + j]);
		var maxPrice = Number(prices["maxPrice." + j]);
		
		// If this is not the last
		var lastIndex = false;
		if(j == totalBands) {
			lastIndex = true;
		}
		if(!lastIndex) {
			var nextMinPrice = Number(prices["minPrice." + (j + 1)]);
			
			if(!lastIndex && (maxPrice >= nextMinPrice)) {
				errors.push("Error Band " + j + " : Upper price is greater than Band "  + (j+1) + " Lower price");
			} 
			// nextMinPrice should only be 1 greater than this maxPrice
			if(!lastIndex && (nextMinPrice != maxPrice + 1)) {
				errors.push("Error Band " + (j+1) + " : Lower price should be " + (maxPrice + 1));
			}			
			
		}		
		if(minPrice >= maxPrice) {
			errors.push("Error Band " + j + " : Lower price is greater than Upper price");
		}
	}	
	if(errors.length > 0) {
		var ewords = errors.join("\n");
		alert(ewords);
		return false;
	} else {
		// valid, prompt!
		return true;
	}
}

function getTotalFeebands() {
	var inputs = document.getElementsByTagName("input");
	var maxBand = 0;
	for(var i=0; i < inputs.length; i++) {
		if(inputs[i].type == "text") {			
			var re = /^[\w]+.([\d]+)/;
			if(re.test(inputs[i].name)) {				
				var band = inputs[i].name.split(/\./);  // returns array				
				if(band[1] > maxBand) {						
					maxBand = band[1];
				}
			}			  
		}
	} 
	return maxBand;	
}

function getNextMinPrice() {
	// next minPrice should have a value of last maxPrice + 1
	var lastMaxPrice = getLastMaxPrice();
	lastMaxPrice++;
	return lastMaxPrice; 
}

function getLastMaxPrice() { 
	var bands = getTotalFeebands();
	var lastMaxPrice = document.getElementById("maxPrice." + bands).value;
	return lastMaxPrice;
}

function addBand() {
	// Create a new row for table
	
	// Create lower price text box
	// Create upper price text box
	// Create commission radio buttons
	// Create commission text box
	// Create deposit radio buttons
	// Create deposit text box	
	
	// Ensure we have a last maxPrice before proceeding
	if(getLastMaxPrice() == "") {
		alert("Plase add an Upper price for the new band");
		return false;
	}
	// Validate all fees before proceeding
	if(!validateFees()) {
		return false;		
	}
	
	var band = getTotalFeebands();
	band++;
	var table = document.getElementById("fees")
	var row1 = document.createElement("tr");
	var td1 = document.createElement("td");
	var td2 = document.createElement("td");
	var td3 = document.createElement("td");
	var td4 = document.createElement("td");
	var td5 = document.createElement("td");

	
	td1text = document.createTextNode(band);

	td1.appendChild(td1text);	
	td2.appendChild(createTextbox("minPrice." + band,"","",getNextMinPrice()));
	td3.appendChild(createTextbox("maxPrice." + band));	
	
	td4.appendChild(createRadio("commissionType." + band,"percentage","commissionTypePercent." + band,true));
	td4.appendChild(createLabel("commissionTypePercent." + band," %"));
	td4.appendChild(createRadio("commissionType." + band,"fixed","commissionTypeFixed." + band));
	td4.appendChild(createLabel("commissionTypeFixed." + band,' \u00A3')); // unicode pound \u00A3
	td4.appendChild(createTextbox("commission." + band));	

	td5.appendChild(createRadio("depositType." + band,"percentage","depositTypePercent." + band,true));
	td5.appendChild(createLabel("depositTypePercent." + band," %"));
	td5.appendChild(createRadio("depositType." + band,"fixed","depositTypeFixed." + band));
	td5.appendChild(createLabel("depositTypeFixed." + band,' \u00A3')); // unicode pound \u00A3	
	td5.appendChild(createTextbox("deposit." + band));

	row1.appendChild(td1);
	row1.appendChild(td2);
	row1.appendChild(td3);
	row1.appendChild(td4);
	row1.appendChild(td5);

	table.appendChild(row1);
	return false;
}

function initJumpMenus() {
    // Turns all <select> elements with the 'jumpmenu' class into jump menus
    var selectElements = document.getElementsByTagName("select");
    for( i = 0; i < selectElements.length; i++ ) {
        // Check for the class and make sure the element has an ID
        if( selectElements[i].className == "jumpmenu" && document.getElementById(selectElements[i].id) != "" ) {
            jumpmenu = document.getElementById(selectElements[i].id);
            jumpmenu.onchange = function() {
                if( this.options[this.selectedIndex].value != '' ) {
                    // Redirect
                    location.href=this.options[this.selectedIndex].value;
                }
            }
        }
    }
}

function promptIfEmptyText(id) {
	var target = document.getElementById(id);
	if(target.value == "") {
		alert("Please enter a value!");
		return false;			
	}
}

function test(id) {
	var target = document.getElementById(id);
	//var t = getHTML(target.value);
	alert(target.value);
	return false;
}












