finalErrorArray = new Array();

function submitToLogin() {
	document.qs_form.action = store_data_url;
	document.qs_form.submit();
}

function isSet( variable )
{
return( typeof( variable ) != 'undefined' );
}

function insertAfter(newElement,targetElement) {
	
	var parent = targetElement.parentNode;
	if(parent.lastchild == targetElement) {
		parent.appendChild(newElement);
	} else {
		parent.insertBefore(newElement, targetElement.nextSibling);
	}

}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function removeRow (rowId) {
	//$.blockUI();
	$('#tempLineItem'+rowId).hide("slow");
	document.getElementById('lineItemContainer').removeChild(document.getElementById('tempLineItem'+rowId));
	//$.unblockUI();
	formProcess(false);
}

function idExists (theVal) {
	if (document.getElementById(theVal) != null) {
		return true;
	} else {
		return false;
	}
}

function qsLoadingAnimation (loading) {
	if (loading==true) {
		document.getElementById('submit_button').style.backgroundColor = '#666666';
		document.getElementById('submit_button').disabled = true;
		document.getElementById('qs-ajax-loader').style.display = 'inline';
	} else {
		document.getElementById('submit_button').style.backgroundColor = '';
		document.getElementById('submit_button').disabled = false;
		document.getElementById('qs-ajax-loader').style.display = 'none';
	}
}

var addRowProcess = function (text, lineId) {
	$('#tempLineItem'+lineId).html(text);
	buildAutoComplete(lineId);
	buildAutoCompleteMFG(lineId);
	qsCheckEverythingDynamic(false);
	
}

function buildAutoComplete (lineId) {

	$("#partnumber_line"+lineId).autocomplete(
		autocomplete_url,
		{
			minChars: 2,
			highlight: false,
			scroll: false,
			formatItem: function(data) { 
				return data[0]
			},
			formatResult: function(data) {
				return data[0]							
			}			
		}
	);	
	
}

function buildAutoCompleteMFG (lineId) {

	$("#mfg_line"+lineId).autocomplete(
		mfg_search_url,
		{
			minChars: 2,
			highlight: false,
			scroll: false,
			formatItem: function(data) { 
				return data[0]
			},
			formatResult: function(data) {
				return data[0]							
			}			
		}
	);	
	
}

function quoteChangeSubmit (formIsGood, text) {
	
	if (formIsGood==true) {
		document.getElementById('submit_error').style.display = 'none';
		document.getElementById('submit_button').value = text;
	} else {
		document.getElementById('submit_error').innerHTML = text;
		document.getElementById('submit_error').style.display = '';
	}
	
}

function insertAjaxCircle (id) {
	document.getElementById(id).innerHTML = '<center>'+document.getElementById('temp-ajax-circle').innerHTML+'</center>';
}

function qsCheckGenericTwo (quoteSample) {
	genericErrors = false;
	if (quoteSample=='q') {
		var thisIs = 'Rfq';
	} else if (quoteSample=='s') {
		var thisIs = 'Rfs';
	}

	var urlString = $('#qs_form').serialize();
	$.ajax({
		type: 'POST', 
		url: validate_generic_url + '/' + thisIs + '/1',
		data: urlString,
		dataType: 'xml',
		success:qsCheckGenericProcess
	});
}

var qsCheckGenericProcess = function (xml) {
	if (xml !==null) {
		var tempGenericErrors = 'false';
		for (i in quoteFieldArray) {
			if ($(xml).find(quoteFieldArray[i]+":first").text() =='true') {
				document.getElementById(quoteFieldArray[i]+'_error').style.display = 'none';
			} else {
				tempGenericErrors = 'true';
				if (quoteFieldArray[i]=='state' && document.getElementById('country')!='US') {
					if (document.getElementById('state_input').value=='') {
						document.getElementById('state_error').innerHTML = '<br />Please fill in this field.';
					} else {
						document.getElementById('state_error').innerHTML = '<br />Please correct this field.';
					}
				} else {
					if (document.getElementById(quoteFieldArray[i]).value=='') {
						document.getElementById(quoteFieldArray[i]+'_error').innerHTML = '<br />Please fill in this field.';
					} else {
						document.getElementById(quoteFieldArray[i]+'_error').innerHTML = '<br />Please correct this field.';
					}
				}
				document.getElementById(quoteFieldArray[i]+'_error').style.display = '';
			}
		}
		genericErrors = tempGenericErrors;
	}
}

function stateAdd (select) {
	var option = document.createElement("option");
	option.text = 'International';
	option.value = 'void1';
	select.options.add(option);
	var i;
	for (i=select.options.length-1; i>=0; i--) {
		if (select.options[i].value == 'void1') {
			select.options[i].selected = true;
		}
	}
}
function stateDelete (select) {
	var i;
	for (i=select.options.length-1; i>=0; i--) {
		if (select.options[i].value == 'void1' || select.options[i].value == 'void2' || select.options[i].value == 'void3') {
			select.remove(i);
		}
	}
}

function addRowTwo (afterWhichRow, quoteSample) {
	
	for (i=1; i<=999999999; i++) {
		if (idExists('tempLineItem'+i)==false) {
			var nextNumber = i;
			break;
		}
	}
	
	//alert(nextNumber);
	
	var newdiv = document.createElement('div');
	newdiv.setAttribute('id', 'tempLineItem'+nextNumber);
	newdiv.innerHTML = '<center>'+document.getElementById('temp-ajax-circle').innerHTML+'</center>';
	insertAfter(newdiv, document.getElementById('tempLineItem'+afterWhichRow));
	
	$.ajax({
		type: "GET",
		url: add_row_url + '/?i=' + nextNumber,
		success: function(o) { 
			addRowProcess(o, nextNumber);
		}
	});
	
}

qsRequestInitiated = false;
lastCall = false;

function qsCheckEverythingDynamic (trySubmit) {
	
	if (qsRequestInitiated==false) {
		clearTimeout(lastCall);
		if (trySubmit==true) {
			qsLoadingAnimation(true);
		}
		lastCall = setTimeout(function(){formProcess(trySubmit)}, 1500);
	}
	
}

function quoteCheckQuantitiesGoTwo (partnumber, quantities, updateDivNumber, clearLoading, quoteSample) {
	
	if (quoteSample=='q') {
		var model_name = 'RequestsForQuotePart';
	} else {
		var model_name = 'RequestsForSamplePart';
	}
	
	if (idExists('updateDiv'+updateDivNumber)==true) {
		var urlString = '&data[' + model_name + '][partnumber]='+partnumber+'&data[updateDivNumber]='+updateDivNumber;
		if (quoteSample=='q') {
			for (i in quantities) {
				urlString += '&data[' + model_name + '][qty'+(Number(i)+1)+']='+quantities[i];
			}
		} else if (quoteSample=='s') {
			urlString += '&data[' + model_name + '][qty]='+quantities;
		}
		
		$.ajax({
			type: 'POST',
			url: check_qty_url,
			dataType: 'xml',
			data: urlString,
			success: function(xml) {
				quoteCheckQuantitiesProcess(xml, clearLoading, "updateDiv"+updateDivNumber, "trackerDiv"+updateDivNumber);
			}
		});
		
	}
	
}

var quoteCheckQuantitiesProcess = function (xml, clearLoading, updateDiv, trackerDiv) {
	
	if (xml !==null) {
		
		if (clearLoading==true) {
			qsLoadingAnimation(false);
		}
		
		var updateDivNum = updateDiv;
		updateDivNum = updateDivNum.replace('updateDiv', '');
		
		if ($(xml).find("trackerDiv:first").text() =='empty' && document.getElementById(updateDiv).style.display=='none') {
			finalErrorArray[updateDivNum] = 'no error';
		} else if ($(xml).find("trackerDiv:first").text() =='empty' && document.getElementById(updateDiv).style.display!='none') {
			document.getElementById(updateDiv).style.display = 'none';
			$("#"+updateDiv).hide("slow");
			document.getElementById(trackerDiv).innerHTML = 'empty';
			if (clearLoading==true) {
				quoteChangeSubmit(true, 'Send my request');
			}
			finalErrorArray[updateDivNum] = 'no error';
			//alert('no error 2');
		} else if (document.getElementById(trackerDiv).innerHTML != $(xml).find("trackerDiv:first").text()) {
			error = true;
			document.getElementById(updateDiv).innerHTML = $(xml).find("pageText:first").text();
			if (document.getElementById(updateDiv).style.display=='none') {
				document.getElementById(updateDiv).style.display ='block';
				$("#"+updateDiv).show("slow");
			} else {
				$("#"+updateDiv).effect("pulsate", {times: 2}, 400);
			}
			if (clearLoading==true) {
				quoteChangeSubmit(false, 'PLEASE FILL IN ALL REQUIRED FIELDS BEFORE PROCEEDING');
			}
			finalErrorArray[updateDivNum] = 'error';
			//alert('error');
		} else {
			finalErrorArray[updateDivNum] = 'error';
		}
		
		//alert(finalErrorArray[updateDivNum]);
		//alert(finalErrorArray.each(function(s, index) { alert(index + ': ' + s); }));
	}
	
}

function checkForm () {
	var divArray = new Array();
	divArray = document.getElementsByClassName('trackerDiv');
	var i = 0;
	quoteErrors = false;
	allDone = true;
	var localQuoteErrors = false;
	for (i in finalErrorArray) {
		//alert(index+': '+s);
		if (finalErrorArray[i]==false) {
			allDone = false;
			break;
		} else {
			if (finalErrorArray[i]=='error') {
				localQuoteErrors = 'true';
				//clearInterval(checkFormTimer);
				//throw $break;
			}
		}
	}
	if (allDone==true) {
		clearInterval(checkFormTimer);
		if (localQuoteErrors=='true') {
			quoteErrors = 'true';
		} else {
			quoteErrors = 'false';
		}
	}
}

function formProcessTwo (trySubmit, quoteSample) {
	
	qsRequestInitiated = true;
	qsLoadingAnimation(true);
	finalErrorArray = [];   
	
	var divArray = new Array();
	divArray = document.getElementsByClassName('trackerDiv');
	var i = 0;
	for (i=0;i<=(divArray.length-1);i++) {
		var currentId = divArray[i].id;
		currentId = currentId.replace('trackerDiv', '');
		//alert(currentId);
		finalErrorArray[currentId] = false;
		if (quoteSample=='q') {
			var tempQtys = {0:document.getElementById('qty1_line'+currentId).value,1:document.getElementById('qty2_line'+currentId).value,2:document.getElementById('qty3_line'+currentId).value,3:document.getElementById('qty4_line'+currentId).value};
		} else if (quoteSample=='s') {
			var tempQtys = document.getElementById('qty_line'+currentId).value;
		}
		quoteCheckQuantitiesGo(document.getElementById('partnumber_line'+currentId).value, tempQtys, currentId, false);
	}
	checkFormTimer = setInterval(function(){checkForm()}, 300);
	qsCheckGeneric();
	qsCheckForAllErrorsTimer = setInterval(function(){qsCheckForAllErrors(trySubmit)}, 300)
	
}

function qsCheckForAllErrors (trySubmit) {
	if (genericErrors!=false && quoteErrors!=false) {
		qsLoadingAnimation(false);
		clearInterval(qsCheckForAllErrorsTimer);
		if (trySubmit==true) {
			if (genericErrors=='true' || quoteErrors=='true') {
				quoteChangeSubmit(false, 'PLEASE FILL IN ALL REQUIRED FIELDS BEFORE PROCEEDING');
				alert('Required fields are either missing or incorrect. Please review all errors.');
			} else {
				document.qs_form.submit();
			}
		} else {
			if (genericErrors=='true' || quoteErrors=='true') {
				quoteChangeSubmit(false, 'PLEASE FILL IN ALL REQUIRED FIELDS BEFORE PROCEEDING');
			} else {
				quoteChangeSubmit(true, 'Send my request');
			}
		}
		qsRequestInitiated = false;
	}
}