// JavaScript Document

function externalLinks() { 
 if (!document.getElementsByTagName) return; 
 var anchors = document.getElementsByTagName("a"); 
 for (var i=0; i<anchors.length; i++) { 
   var anchor = anchors[i]; 
   if (anchor.getAttribute("href") && 
       anchor.getAttribute("rel") == "external") 
     anchor.target = "_blank"; 
 } 
}

function rollOver(iImg) {
/***************************************************
	Function for rollover of the WEEE logos.
	Changes image to other precachaed image.
***************************************************/
	if (iImg.tagName == 'IMG') {
		mImgID = iImg.id
	} else {
		mImgID = iImg.id.slice(0,-1);
	}
	
	var mImg = document.getElementById(mImgID);
	mImg.src = document.mImgs[mImgID].src;
	
}

function rollOut(iImg) {
/***************************************************
	Function for rollover of the WEEE logos.
	Changes image to other precachaed image.
***************************************************/	
	if (iImg.tagName == 'IMG') {
		mImgID = iImg.id
	} else {
		mImgID = iImg.id.slice(0,-1);
	}
	
	var mImg = document.getElementById(mImgID);
	mImg.src = document.mImgs[mImgID + '_'].src;
	
}

function listSubmit() {
/***************************************************
	Function for checking that a country has been
	selected on the list only version of the 
	country selection page.
***************************************************/
	var mList = document.forms['countryChoice'].countryList;
	var tSelected = mList.selectedIndex;
	if (tSelected > -1) {
		var tCountryCode = mList.options[tSelected].value.slice(0,-1);
		var tPageRef = '../customer/cust' + tCountryCode + '.htm';
	
		document.forms['countryChoice'].action = tPageRef;
		
		return 1;
	} else {
		rabbit = alert('Please select a country');
		return 0;
	}
}

function countryChange() {
	var mList = document.forms['countryChoice'].countryList;
	var tSelected = mList.selectedIndex;
	if (tSelected > -1) {
		var tCountryOption = mList.options[tSelected];
		mapOver(tCountryOption);
	}
}

function mapOver(e) {
	removeOldCountry();
	
	var countryID = e.id.slice(0,-1);
	var mOptIndex = document.getElementById(countryID + 'f').index;
	var mapHolder = document.getElementById('eui').parentNode;
	var mList = document.forms['countryChoice'].countryList;
	
	mStateI[countryID].className = "weeeRollMap";
	mapHolder.appendChild(mStateI[countryID]);
	mList.options[mOptIndex].selected = true;	
}

function removeOldCountry() {
	var mapHolder = document.getElementById('eui').parentNode;
	var mapImages = mapHolder.getElementsByTagName('img');
	if (mapImages.length > 2) {
		for (i = 2; i < mapImages.length; i++) {
			mapHolder.removeChild(mapImages[i]);
		}
	}
}

function removeSpaces(e) {
	var tstring = "";
	string = '' + e;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}

Array.prototype.indexOf = function (e) {
	
	var present = -1;
	for (var i = 0; i < this.length; i++) {
		if (removeSpaces(this[i].toLowerCase()) == removeSpaces(e.toLowerCase())) {
			present = i;
		}
	}
	return present;
};

function unique(a) {
	b = new Array();
	
	for (var i = 0; i < a.length; i++) {
		if (b.indexOf(a[i], 0) < 0) {
			b.push(a[i]);
		}
	}	
	return b;
}

function compare (a, b) {
	return a - b;
}


function checkProducts() {
/**************************************************
	function called by fCheck()
	Checks that valid product numbers have been
	supplied by the customer.
	Returns boolean: true = all products are valid.
**************************************************/
	var pList = document.getElementById('products').value;
	var regex = / *, */;
	var pEntered = pList.split(regex);
	var pValid = pNumber.join(',');
	pValid += ',';
		
//	rabbit = alert(pValid + '\n' + pList + '\n' + document.getElementById('products').value);
	
	pEntered = unique(pEntered);
	
	rFalse = false;
	var pSplice = new Array();
	
	errorMessage =  '';
	
	for (var i = 0; i < pEntered.length; i++) {
		var pHigh = new Array()
		pTemp = pEntered[i];
		
		for (var j = 0; j < pTemp.length; j++) {
			pHigh[j] = (pTemp.charCodeAt(j) > 127) ? true : false;
		}
				
		for (var j = 0; j < pHigh.length; j++) {
			if (pHigh[j]) {
				pCode = pTemp.charCodeAt(j);
				pTemp3 = pTemp.slice(j + 1);
				pTemp1 = (j !== 0) ? pTemp.substring(0,j) : '';
				pReplace = '&#';
				pReplace += pCode;
				pReplace += ';';
				pEntered[i] = pTemp1 + pReplace + pTemp3;
			}
		}		

//	rabbit = alert (pTemp + '\n' + pEntered[i]);

	while (pNumber.indexOf(pEntered[i]) == -1) {
	
		var resultArray = pEntered[i].match(/&#[0-9]{2,3};/g);
		if (resultArray) {
	  	for (j = 0; j < resultArray.length; j++) {
		  	var index = pEntered[i].indexOf(resultArray[j]);
				pCode = pEntered[i].substr(index+2,resultArray[j].length-3);
			
				pReplace = String.fromCharCode(pCode);
				p1 = pEntered[i].substring(0,index);
				p3 = pEntered[i].substring(index+resultArray[j].length);
			
				pPrompt = p1 + pReplace + p3;
			}
		} else {
			pPrompt = pEntered[i];
		}
	
		errorMessage = 'Incorrect product number: ' + pPrompt + '\n';
		errorMessage += 'Please correct or cancel it.'
		prompted = prompt(errorMessage, pPrompt);	
		if (prompted == null) {
			pEntered.splice(i, 1);
			pSplice[i] = true;
			rFalse = true;
		} else {
			pSplice[i] = false;
		//	rabbit = alert(prompted);

			var pHigh = new Array()
			pTemp = prompted;
			
			for (var j = 0; j < pTemp.length; j++) {
				pHigh[j] = (pTemp.charCodeAt(j) > 127) ? true : false;
			}
					
			pReplaced = false;
			for (var j = 0; j < pHigh.length; j++) {
				if (pHigh[j]) {
					pCode = pTemp.charCodeAt(j);
					pTemp3 = pTemp.slice(j + 1);
					pTemp1 = (j !== 0) ? pTemp.substring(0,j) : '';
					pReplace = '&#';
					pReplace += pCode;
					pReplace += ';';
					pEntered[i] = pTemp1 + pReplace + pTemp3;
					pReplaced = true;
				}
			}
			if (!pReplaced) pEntered[i] = prompted;
		}
		if (pSplice[i])
			break;
		}	
	}
	
	for (var j = 0; j < pEntered.length; j++) {
		if (pSplice[j]) {
			pEntered.splice(j, 1);
		}
	}
	
	pEntered = unique(pEntered);
	pEntered.sort(compare);
	var pNew = pEntered.join(', ');
	var resultArray = pNew.match(/&#[0-9]{2,3};/g);
	if (resultArray) {
	  for (i = 0; i < resultArray.length; i++) {
		  var index = pNew.indexOf(resultArray[i]);
			pCode = pNew.substr(index+2,resultArray[i].length-3);
			
			pReplace = String.fromCharCode(pCode);
			p1 = pNew.substring(0,index);
			p3 = pNew.substring(index+resultArray[i].length);
			
			pNew = p1 + pReplace + p3;
		}
	}
				
	document.getElementById('products').value = pNew;
	
	return rFalse;
	
}


function toggleVis(iObject, oGroup, iMode) {
/**************************************************
	Function toggles display of text box
	iObject is calling object
	oGroup is id of element containing textbox
	iMode is boolean corresponds to whether text box
		should be displayed when iObject is checked
**************************************************/	
  var mVisTag = ((iObject.checked) == (iMode)) ? "inline" : "none";
  var mTarget = document.getElementById(oGroup);
  mTarget.style.display = mVisTag;
  if (mVisTag == "none") {
    with (document.getElementById("recycleReasonDetail")) {
      value = defaultValue;
    }
  }
}


function detailCheck() {
	setInterval("toggleVis(document.getElementById('recycleReason3'), 'recycleReasonOther', true)", 10);
}

function phoneCheck(iTestVal) {
/**************************************************
	function called by fCheck()
	Checks iTestVal input string against mFormat
	mFormat defines the allowed email address format
	Returns boolean: true = good email
**************************************************/
    return true;
}

function emailCheck(iTestVal) {
/**************************************************
	function called by fCheck()
	Checks iTestVal input string against mFormat
	mFormat defines the allowed email address format
	Returns boolean: true = good email
**************************************************/
  var mFormat = /(^[a-z]([a-z_\-\.]*)@([a-z_\-\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\-\.]*)@([a-z_\-\.]*)(\.[a-z]{2,3})(\.[a-z]{2})*$)/i;
  return (mFormat.test(iTestVal));
}

/**************************************************
    function called bgy radio buttons indicating how the customer wants to submit their product information
**************************************************/
function productValidator()
{
    if(document.forms[0].productValidation[0].checked)
    {
        document.getElementById('quantity').disabled = false;
        document.getElementById('quantity').style.backgroundColor = "white"
    }
    else
    {
        document.getElementById('quantity').disabled = true;
        document.getElementById('quantity').style.backgroundColor = "#d0d0d0"
    }
}

function addSerialNumberFields()
{
    var count = parseInt(document.getElementById('quantity').value);
    if(count > 0 && count != NaN)
    {
        var parent = document.getElementById('productInfoDiv');
        var newHtml = ""
        var i;
        for(i=0;i < count;i++)
        {
            newHtml = newHtml +  "<div id='productDiv" + i + "' class='row' style='margin-top:15px; height:45px;'>";
            newHtml = newHtml + "<span class='label'><label for='ProductNumber'>* Product:</label></span><span class='formfield'><select  name='ProductName" + i + "' id='ProductName" + i + "'><option selected='selected'>Select Product</option><option value='GPC/GPCPN'>GPC/GPC PN</option><option value='G5/G5R'>G5/G5R</option><option value='Q100'>Q100</option><option value='FC200/FC200R'>FC200/FC200R</option><option value='Other'>Non-Itron Product</option></select></label></span>";
            newHtml = newHtml + "<span class='label'><label for='SerialNumber" + i + "'>* Serial Number:</label></span><span class='formfield'><input name='SerialNumber" + i + "' id='SerialNumber" + i + "' maxlength='12' size='13' /></span>";
            newHtml = newHtml + "</div>";
        }
        outline = document.getElementById('productNVal');
        outline.style.height = 213 + (63 * count) + "px";
        parent.innerHTML = newHtml;
        
    }
}

function fConfirmReset() {
/**************************************************
	Function runs when form reset is actioned
	Sends confirmation message to user
	Will cancel resetting of form if answer is "no"
**************************************************/
  if (confirm('Are you sure you wish to clear the form?')) {
		document.getElementById('fReason').style.borderStyle = "none";
		document.getElementById('fPerformance').style.borderStyle = "none";
		document.getElementById('fSatisfaction').style.borderStyle = "none";
		document.getElementById('fWhichProduct').style.borderStyle = "none";
		return true;
	} else {
		return false;
	}
}


function fCheckSubmit() {
	
/**************************************************
	Function runs on submission of form
	Checks that all fields are filled with data
	Uses fCheck() to fill text boxes where necessary
	Highlights radio groups that need to be filled
	Cancels submission if outstanding data
***************************************************/

	var mForm = document.forms['fLabel'];
	mRecycle = mPerformance = mService = mDetail = mProducts = false;
	mProductNames = mProductSerials = true;
	
	    if(document.forms[0].productValidation[0].checked)
	    {
		    var quantity = parseInt(document.getElementById('quantity').value);
	        if(quantity != NaN)
	        {
	            for(var j = 0; j < quantity; j++) {
	                if(document.getElementById("ProductName" + j).selectedIndex == 0) {
	                  alert("Please select all the products being recycled.");
	                  return false;
	                }
	                if(document.getElementById("SerialNumber" + j).value == "" || document.getElementById("SerialNumber" + j).value == "null") {
	                  alert("Please enter the serial numbers of all the products being recycled.");
	                  return false;
	                }
	            }
	        }
	    }
	
	for (var j = 0; j < mForm.elements.length; j++) {
		/*
			run fCheck() on all elements
			to make sure text fields
			are filled in correctly
		*/
		if (!fCheck(mForm.elements[j])) {
		    if(mForm.elements[j]['id'] != 'email' || (document.forms[0].productValidation[0].checked && mForm.elements[j]['id'] == 'quantity'))  {
			    return false;
			}
		}
	}
	
	
	for (var i = 0; i < 3; i++) {
		/*
			Only three options for each radio group
			For each group, set tag to true if an
			option has been selected
		*/		
		if (!mRecycle) {
			mRecycle = mForm.elements['reason_for_recycling'][i].checked;
		}
		if (!mPerformance) {
			mPerformance = mForm.elements['product_performance_during_operational_life'][i].checked;
		}
		if (!mService) {
			mService = mForm.elements['satisfaction_with_service_during_operational_life'][i].checked;
		}
	}
	
	for (var i = 0; i < 2; i++) {
		/*
			Only two options for this radio group
			For the group, set tag to true if an
			option has been selected
		*/		
		if (!mProducts) {
			pR1 = mForm.elements['product_sent_for_recycling1'];
			pR2 = mForm.elements['product_sent_for_recycling2'];
			
			if (pR1.checked || pR2.checked) {
				mProducts = true;
			}
		}
	}
	

	
	/*if (!mRecycle) {
		/*
			Has the recycle reason been given?
			If not, highlight the radio button group
		
		
		with (document.getElementById('fReason').style) {
			color = "red";
			borderWidth = "1px";
			borderStyle = "solid";
		}

	}

	if (!mPerformance) {
		/*
			Has the performance assessment been given?
			If not, highlight the radio button group
		
		with (document.getElementById('fPerformance').style) {
			color = "red";
			borderWidth = "1px";
			borderStyle = "solid";
		}
	}
	
	if (!mService) {
		/*
			Has the service assessment been given?
			If not, highlight the radio button group
		
			with (document.getElementById('fSatisfaction').style) {
			color = "red";
			borderWidth = "1px";
			borderStyle = "solid";
		}
	}
	
	if (!mProducts) {
		/*
			Has the service assessment been given?
			If not, highlight the radio button group
		
			with (document.getElementById('fWhichProducts').style) {
			color = "red";
			borderWidth = "1px";
			borderStyle = "solid";
		}
	}
	
	if ((!mRecycle) || (!mPerformance) || (!mService) || (!mProducts)) {
		/*
			if any of the button groups don't have a selected option
			send a message to the user to complete them
			and then cancel the form submission
		
		alert('Please complete highlighted sections');

		return false;
	}*/

	return true;
	
}



function fCheck(iObject) {
/**************************************************
	Function checks that text fields are filled
	Uses emailCheck()to check that 
		email address is valid format
	Uses prompt boxes to require user to fill in 
		missing data.
	Prompts will continue until data is provided
***************************************************/	
  var mTestVal = iObject.value;
	var rFalse = false;

	bSwitch:

  switch (iObject.id) {
    case "user":
		// has a user's name been supplied?
      if ((mTestVal == "null") || (mTestVal == "")) {
        do {
					var mRetry = prompt('Please enter your name', '');
					if (mRetry != null) {
						// put the supplied name in the right place
						iObject.value = mRetry;
					} else {
						// or cancel the operation
						rFalse = true;
						break bSwitch;
					}
        } while ((iObject.value == "null") || (iObject.value == ""))
      }
    break;
    case "company":
		// has an end-user company been supplied?
      if ((mTestVal == "null") || (mTestVal == "")) {
        do {
					var mRetry = prompt('Please enter your company name', '');
					if (mRetry != null) {
						// put the supplied name in teh right place
						iObject.value = mRetry;
					} else {
						// or cancel the operation
						rFalse = true;
						break bSwitch;
					}
        } while ((iObject.value == "null") || (iObject.value == ""))
      }
    break;
    case "phoneNumber":
		if ((mTestVal == "null") || (mTestVal == "")) {
        do {
					// ask for a new address until a valid one is supplied
					var mRetry = prompt('Please enter a valid phone number', '');
					if (mRetry != null) {
	          if (phoneCheck(mRetry)) {
							// put the valid address in the right place
  	          iObject.value = mRetry;
	          }
					} else {
						// or cancel the operation
						rFalse = true;
						break bSwitch;
					}
        } while ((iObject.value == "null") || (iObject.value == ""))
      }
      break;
      case "quantity":
		if (document.forms[0].productValidation[0].checked && ((mTestVal == "null") || (mTestVal == "") || (mTestVal == "0"))){
					alert('Please enter the quantity of products being recycled.');
						rFalse = true;
						break bSwitch;
        }
      break;
    default:
      break;
  }
  
  
	
	

		return !rFalse;
}