// JavaScript Document - for ***** WineMarket.com.au onLoadReg.js *****
// Author : don mclean, onlineone
// Copyright: online one
//
// Script runs onload within the browser and detects the page on the check out and then does DOM manipulation
// based on the user/customer requirement.

// Put the script into NetSuite document library, then refer to it in the theme header
// and be sure to add an onload="onLoadReg();" call in the browser ..

// IE Issues....removing and then recreating a table row tr
// Creating the suburb drop down list

function processZip()
{
	// determine the browser
	var obj = document.getElementById('city')
	var browser = "";
	if (obj.addEventListener) //W3C
	{
		browser="W3C";
	}
	else if (obj.attachEvent) // IE
	{
		browser="IE";
	}
	//alert(browser);
	
	var x = this.value;
	

	
	if (x.length > 4)
	{
		alert('postcode cannot be greater than 4 digits. Please edit the postcode.')
	}
	if (x.length == 4 )
	{

		var state = lookupState(x);
		var state_select = document.getElementById("dropdownstate");
		var state_field = document.getElementById("state");
		state_select.value = state;
		//alert(state);
		if (state != null)
		{
			state_field.value = state;
			switch ( state ) 
				{
				// 	
				case ('ACT') : state_select.options[1].selectedIndex = 1; 
				break;
				// 	
				case ('NSW') : state_select.options[2].selectedIndex = 2; 
				break;			
				// 	
				case ('NT') : state_select.options[3].selectedIndex = 3; 
				break;
				// 	
				case ('QLD') : state_select.options[4].selectedIndex = 4;  
				break;
				// 	
				case ('SA') : state_select.options[5].selectedIndex = 5;  
				break;
				// 	
				case ('TAS') : state_select.options[6].selectedIndex = 6;  
				break;	
				// 	
				case ('VIC') : state_select.options[7].selectedIndex = 7; 
				break;	
				// 	
				case ('WA') : state_select.options[8].selectedIndex = 8; 
				break;	
				

				}
		} // of if state != null
		else

		{
			alert('Please reenter postcode. This postcode does not exist');
			
		}
			// get the appropriate selected option and add the option.selected ="true" to that option...
			
	
		var suburb = lookupTown(x);
		if (suburb != null)
		{
			var suburblist = document.getElementById("suburblist");
			
			var listel;
			// add the first element only
			listel = document.createElement('option') // create the option to add
			listel.value= "select suburb";
			listel.text = "-- select suburb --";
			listel.innerHTML = "-- select suburb --";
			suburblist.appendChild(listel);
			//alert(suburb.length);	
			// create a window with the suburbs to select if > 1 on the suburb list
			var length = suburb.length;
			
			if (browser =="IE") length--; // remove 1 from the length
			
			if (length > 0) 
			{
				for (var i = 0; i < length; i++) 
				{
					listel = document.createElement('option') // create the option to add
					if (suburb[i].name != "" || suburb[i].name != null) 
					{
						listel.value = suburb[i].name;
						listel.text = suburb[i].name;
						listel.innerHTML = suburb[i].name;
						
						suburblist.appendChild(listel);
					}
				}
				suburblist.focus();
			} // of if length > 0
		}
	


	}
	/*if (x.length == 3) 
	{
		alert("length is 3");
	}
	*/
	if (x.length < 4)
	{
		var suburbs = document.getElementById("suburblist");
		// get all the child elements and remove them all
		if (suburbs.length > 0)
		{	
			end = suburbs.length;
			for ( var i = 0; i < end; i++)
			{
				suburbs.removeChild(suburbs[0]); // remove the first one n times
			}
		}

		document.getElementById("dropdownstate").value = "";
	}
	
}

function processZipAfter ()
{
	var obj = document.getElementById('city')
	var browser = "";
	if (obj.addEventListener) //W3C
	{
		browser="W3C";
	}
	else if (obj.attachEvent) // IE
	{
		browser="IE";
	}
	//alert(browser);
	
	var x = this.value;
	
	if (x.length <= 3) 
	{
		alert("Postcode has to be 4 digits. For instance an NT postcode of 800 should be entered as 0800. Thank you.");
		document.getElementById('zip').focus();
	}
	
	
}

function lookupTown(zip)
{
	var suburb;
	try
	{
		suburb = p_array[zip].suburb;
	}
	catch (e)
	{	
		suburb = null;
	}
	return suburb;
}

function lookupState(zip)
{
	var zipcode = zip;

	var state;
	try 
	{
		state = p_array[zipcode].state;
	}
	catch (e)
	// if the state is not there then return null
	{
		state = null;
	}
	return state;
}


function isPO()
{

    x = this.value;
    var lowstr = x.toLowerCase();
    var c = lowstr.indexOf("po");
    var d = lowstr.indexOf("p.o.");
    
    //alert(lowstr+' = '+c+' '+d);
    if ( (c == -1 && d == -1) || (c > 2 || d > 2) ) // if detected po after the first 2 positions or no po then quit
    {
        return;
    }
    else 
    {
        alert('Please note we cannot deliver to PO Boxes. Please amend your address accordingly. Thank you.');
        
        document.getElementById("addr1").value = ""; // blank the field
        document.getElementById("addr1").focus();
        return false;
    }
    
}

	function over() {
		this.style.backgroundColor='#ffffff'
	}
	
	function out() {
		this.style.backgroundColor='#ffffff'
	}
	// check that it is a valid velcoity number
function checkVelocity() {
	//alert('called');
	var x = this.value;
	if (x.length < 10 && x.length != 0)
	{
		
		// focus back on the field
		document.getElementById("custentity_velocitynumber").focus();
		alert('Velocity number has to be at least 10 digits');
		return true;
	}
	else
	if ( allNumbers(x) >= 0)
	{
		document.getElementById("custentity_velocitynumber").focus();
		alert('Velocity number should have no alpha characters');
		return true;
	}
	addVelocityName( document.getElementById('name').value );
}
// returns -1 if there are no alphas and only digits
function allNumbers(x)
{
	return x.search(/\D/g);
}

// adds the customers name to the velocity field after the name has been completed
function addVelocityName (velname) {
		var x = velname;
		
		document.getElementById("custentity_velocityname").value = x;
}

function formatPhone()
{
		var x = this.value;
		var posn = x.length;
		//alert(x);
		if (posn >= 13 )	
		{
			alert('Phone number can be no longer than 10 digits. Please change the phone number');
			x.value = x.slice(0,11);
			x.innerHTML = x.slice(0,11);
			return true;
		}

		//alert(x.length)
		

		//if (posn == 1) this.value = "["+x;
		if (posn == 2 || posn == 7) this.value = x+ " ";	
		
				  
}
function selectSuburb()
{
	var x = this.value
	//alert(x);
	document.getElementById('city').value = x;
}


// main function
function onLoadReg()
			
	
			{
				// CONSTANTS
				TABLE = 22;
				
			    var title = document.title;
			    var url = document.URL;
			    var shipping = url.indexOf("shipping")
			    var tds = document.getElementsByTagName('td');
			    
			    for (var i = 0; i < tds.length; i++) 
			    {
			        if (tds[i].innerHTML == "Choose Shipping Address") 
			        {
			            //alert('detected choose shipping address'); 
			            shipping = -1; // set shipping to false as we are now in the edit screen
			        }
			        if (tds[i].innerHTML == "Enter New Shipping Address") 
			        {
			            //alert('detected enter shipping address');
			        }
			    }
				
			    var t = title.split(' ');
				switch ( t[0] ) 
				{
				// Login		
				case ('Login') : 
					var x = document.getElementsByTagName('input');
					for (var i=0;i<x.length;i++) {
						x[i].onmouseover = over;
						x[i].onmouseout = out;
						
					}

					// get the title of the page loaded
					var obj = document.getElementById("custentity_velocitynumber");
					//if (obj != null)
					//	obj.addEventListener( "blur", checkVelocity, false );
					obj.onblur = checkVelocity;
					

					
				break;
				// STEP 1 - The shopping basket is being viewed			
				case ('Shopping') : 

				break;
				// STEP 2 - The "Buy Now" button has been pressed and now viewing the registration page					
				case ('Checkout') :  

				break;
				// STEP 3 - The "Buy Now" button has been pressed and now viewing the registration page	
				case ('Address') : 
				//add the script
				if (shipping > 0) // only run this when the screen is create and not edit
				{
					var obj = document.getElementById("addr1");
					//if (obj != null)
						//obj.addEventListener( "blur", isPO, false );
					obj.onblur = isPO;	
					
					//obj.onblur = isPO;
					//if (obj.captureEvents) obj.captureEvents(Event.ONBLUR);
					
					var obj = document.getElementById("phone");
					//if (obj != null)
						//obj.addEventListener( "keyup", formatPhone, false );
					obj.onkeyup = formatPhone;
			
					var obj = document.getElementById("zip");
					//if (obj != null)
						//obj.addEventListener( "keyup", processZip, false );
					obj.onkeyup = processZip;	
					//obj.onblur = processZipAfter;

				// get the name field and hide it
				//document.getElementById("attention_input_fs").style.visibility="hidden";
				//document.getElementById("attention_input").value="input";
				
				// get the main form in order to get to the rows and change them
				var table = document.getElementsByTagName('table'); var str="";
				for (var i =0; table != null && i < table.length; i++)
				{	str=""
					str+='['+i+']  1:'+table[i].innerHTML+' ';

					//if (i > 12) alert(str)	;			
				}
				// table 16 has the form rows... so get all the rows and put them into....ta da....the rows...
				var rows = table[TABLE].getElementsByTagName('tr');
				
				// add an id to the table so it can be easily referenced in the future..
				table[TABLE].id = "main-table"
				
								// debug loops to show the row contents
				for (var i =0; rows != null && i < rows.length; i++)
				{	str=""
					str+='['+i+']  1:'+rows[i].innerHTML+' ';
					str+='  2:'+rows[i].id+' ';
					str+='  3:'+rows[i].value+' \n';	
					//alert(str)				
				}
				// hide row[5] ...the city/suburb row
				

				rows[5].style.display = "none";
				//alert('city removed')
				// create the suburb/town drop down list
				tr = document.getElementById('main-table').insertRow(5);
				var cell0=tr.insertCell(0);
				var cell1=tr.insertCell(1);
				cell0.innerHTML="Town/Suburb";
				cell0.className ="smalltextnolink"
				cell0.align= "right";

	
				// construct the drop down select ready for the usuburbs to be selected
				var newnode3 = document.createElement('select');
				newnode3.value ="testnew nodevalue";
				newnode3.label = "suburblist";
				newnode3.id = "suburblist";
			
				cell1.appendChild(newnode3);
				
				var obj = document.getElementById("suburblist");
					//if (obj != null)
						obj.onblur = selectSuburb;	
				

				
				// the postcode row is row #9
				postcoderow = rows[9]
				pc_cell0 = postcoderow.firstChild;
				pc_cell1 = postcoderow.lastChild;

			
				// now reinsert the row
				
				var pcrow = document.getElementById('main-table').insertRow(5);
				pcrow.id = 'postcode-row';
				
				var cell0 = pcrow.insertCell(0);
				var cell1 = pcrow.insertCell(1);
				cell0.innerHTML = pc_cell0.innerHTML;
				cell1.innerHTML = pc_cell1.innerHTML;	
				pcrow.appendChild(pc_cell0);			
				pcrow.appendChild(pc_cell1);
				// delete the original
				pcrow.deleteCell(0);
				pcrow.deleteCell(0);			
				// debug loops to show the row contents
				for (var i =0; rows != null && i < rows.length; i++)
				{	str=""
					str+='['+i+']  1:'+rows[i].innerHTML+' ';
					str+='  2:'+rows[i].id+' ';
					str+='  3:'+rows[i].value+' \n';	
					//alert(str)				
				}
				

				// get the country and set it to Australia by default
/*			var country = document.getElementById("country")
				country.selectedIndex= 13; // set to Australia
*/				
				}
				break;
				
				case ('Payment') : 
				
					break;
				
		
				case ('Review') : 
				

				break;

				}
				
				
	
			}
	