/**
 * JS on the search results page. This has several AJAX calls related to
 * business profile, RFQ and connection request.
 */
dojo.addOnLoad(init);

function init() {
	
	dojo.require("dojo.parser");
	dojo.require("dojo.string");

	var location = dojo.byId("location");
	if (location != null)
		dojo.connect(location, "onclick", locationTextBoxClicked);

	// Setup event connections.
	var continueRFQ = dojo.byId("buttonContinueRFQ");
	
	if (continueRFQ != null) {
		
		dojo.connect(continueRFQ, "onclick", onRequestQuoteContinueToQuestions);
	}

	var submitBtn = dojo.byId("buttonSubmitRFQ");
	if (submitBtn != null) {
		dojo.connect(submitBtn, "onclick", submitDialog);
	}

	var connectSubmitBtn = dojo.byId("connectSubmitButton");
	if (connectSubmitBtn != null) {
		dojo.connect(connectSubmitBtn, "onclick", submitConnectForm);
	}

	var saveBtn = dojo.byId("saveBtn");
	dojo.connect(saveBtn, "onclick", saveContent);

	var clearBtn = dojo.byId("clearBtn");
	dojo.connect(clearBtn, "onclick", clearContent);

	var countryDropDown = dojo.byId("country");
	dojo.connect(countryDropDown, "onchange", updateCode);
	
	updateCode();
	
	var mapCanvasDiv = dojo.byId("map_canvas");
	if (mapCanvasDiv != null) {
		initializeGmaps();
	}
	
	
}


/*******************************************************************************
 * G! Maps
 ******************************************************************************/
var geocoder;
var map;
function initializeGmaps() {
	geocoder = new google.maps.Geocoder();
    var myOptions = {
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	var address = "San Fransisco, USA";
	var address = dojo.byId("txtHiddenBusinessAddress").value;
	
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        //alert("Geocode was not successful for the following reason: " + status);
      }
    });
}

/*******************************************************************************
 * RFQ Related
 ******************************************************************************/

// update ISD code for country using helper method
function updateCode() {
	var countryDropDown = dojo.byId("country");
	var selectedKey = countryDropDown.options[countryDropDown.selectedIndex].value;
	if (selectedKey == "")
		selectedKey = 0;

	var code = dojo.byId("code");
	var countryCode = getCodeForCountry(selectedKey);

	var phone = dojo.byId("phone").value;

	countryCode1 = countryCode;
	countryCode2 = countryCode.replace("+", "00");
	// countryCode3 = countryCode.replace("+", "");

	if (phone.indexOf(countryCode1) == 0)
		phone = phone.slice(countryCode1.length);

	if (phone.indexOf(countryCode2) == 0)
		phone = phone.slice(countryCode2.length);

	// if (phone.indexOf(countryCode3) == 0)
	// phone = phone.slice(countryCode3.length);

	while (phone.indexOf("+") == 0 || phone.indexOf("0") == 0)
		phone = phone.slice(1);

	dojo.byId("phone").value = phone;

	if (countryCode == "")
		code.innerHTML = "";
	else
		code.innerHTML = countryCode;
}

/*
 * When user hits "RFQ" link.
 */
function onRequestQuoteClick(businessId, businessName) {

	//Clearing any old table of questions if present
	  var d = document.getElementById('questionAnswersDiv');
	  var olddiv = document.getElementById('questionAnswersTable');
	  if(olddiv != null){
	  	d.removeChild(olddiv);
	  }	
	
	// Clear RFQ Forms and hide other dialogs.
	resetRFQForm();
	hideAllDialogs();
	var continueRFQ = dojo.byId("buttonContinueRFQ");

	if (continueRFQ != null) {
		
		dojo.connect(continueRFQ, "onclick", onRequestQuoteContinueToQuestions);
	}

	var errMsg = dojo.byId('checkConnectionError');
	errMsg.innerHTML = "";

	// Attach RFQ form under correct parent node
	var rfqFormP1 = dojo.byId('rfqFormP1');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(rfqFormP1);

	// Hidden form field: Business Id
	dojo.byId("businessId").value = businessId;

	// Make RFQ form visible
	rfqFormP1.style.visibility = "visible";
	rfqFormP1.style.display = "block";

	// Hide the "interested in" part
	var interestedIn = dojo.byId("interestedIn");
	interestedIn.style.display = "none";
	interestedIn.style.visibility = "hidden";

	// Change focus to that business so the form becomes visible to the user.
	window.location.href = "#hd" + businessId;
	window.location.href = "#biz" + businessId;

	// Get the child classes via XHR call.
	fetchClassesForBusiness(businessId);

}

//
// Fetch child classes for the business.
//
function fetchClassesForBusiness(businessId) {

	// Disable the continue button
	var btnContinue = dojo.byId('buttonContinueRFQ');
	btnContinue.disabled = true;

	// Activate busy icon.
	var busyIcon = dojo.byId("busyChildCategories");
	busyIcon.style.visibility = "visible";
	busyIcon.style.display = "block";

	// XHR call to fetch the child categories.
	var reqData = {
		"businessId" :businessId
	};

	dojo.rawXhrPost( {
		url :"/api/lookup/getIndustriesForBusiness",

		headers : {
			"Content-Type" :"application/json"
		},

		postData :dojo.toJson(reqData),

		handleAs :"json",

		// If success from server.
		load : function(data, ioArgs) {
			handleClassesForBusiness(data, businessId);
		},

		// If error from server.
		error : function(data, ioArgs) {
			// Hide busy icon.
		busyIcon = dojo.byId("busy");
		busyIcon.style.visibility = "hidden";
		alert(data);
	}

	});

}

//
// Got list of child classes.
//
function handleClassesForBusiness(data, businessId) {

	var parentIndustry = dojo.byId("parentIndustry");
	parentIndustry.value = data[0].k;
	var childContainer = dojo.byId("businessChildIndustries");

	// Populate the list of child-industries on the screen.
	for (i = 1; i < data.length; i++) {
		//
		// Construct the checkbox and it's label dynamically.
		//
		try {
			radio = document
					.createElement('<input type="radio" name="childIndustry" id="childIndustry" value=' + data[i].k + ' />');
		} catch (err) {
			radio = document.createElement('input');
			radio.type = "radio";
			radio.name = "childIndustry";
			radio.id = "childIndustry";
			// radio.checked=false;
			radio.value = data[i].k;
		}

		childContainer.appendChild(radio);

		var myText = dojo.doc.createTextNode(data[i].v);
		childContainer.appendChild(myText);

		childContainer.appendChild(dojo.doc.createElement("br"));
	}

	var interestedIn = dojo.byId("interestedIn");

	if (data.length > 1) {
		interestedIn.style.display = "block";
		interestedIn.style.visibility = "visible";
		interestedIn.innerHTML = "I'm interested in " + data[0].v
				+ ", specifically:";
	} else {
		interestedIn.style.display = "block";
		interestedIn.style.visibility = "visible";
		interestedIn.innerHTML = "I'm interested in " + data[0].v;
	}

	// "To be determined"
	// checkbox = dojo.doc.createElement("input");
	// checkbox.type="checkbox";
	// checkbox.name="childIndustry";
	// checkbox.id="childIndustry";
	// checkbox.checked=false;
	// checkbox.value="-1";
	// childContainer.appendChild(checkbox);

	// var myText = dojo.doc.createTextNode("To Be Determined");
	// childContainer.appendChild(myText);
	// childContainer.appendChild(dojo.doc.createElement("br"));

	// Hide busy icon.
	var busyIcon = dojo.byId("busyChildCategories");
	busyIcon.style.visibility = "hidden";
	busyIcon.style.display = "none";

	// Enable the continue button
	var btnContinue = dojo.byId('buttonContinueRFQ');
	btnContinue.disabled = false;

}

//
// When user hits "Continue" on page 1.
//
function onRequestQuoteContinue() 
{
	var childClasses = getSelectedChildClasses();
	var totalChoices = getTotalChildClasses();

	// Validate RFQ Page 1.
	if (totalChoices.length != 0 && childClasses.length == 0) {
		var err = dojo.byId("rfqFormP1Error");
		err.innerHTML = "Please select at least one category that you are interested in.";
		return;
	}


	// Hide all divs.
	hideRFQForms();

	businessId = dojo.byId("businessId").value;
	

	// Attach RFQ form page 2 under correct parent node
	var rfqFormP2 = dojo.byId('rfqFormP2');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(rfqFormP2);
	
	//check if the Q n A form was filled so as to disable RFQ details accordingly
	if(dojo.byId("questionExist").value=="true"){
		  dojo.byId("rfqDetailsIdText").style.visibility = "hidden";
			dojo.byId("rfqDetailsIdText").style.display = "none";
			  dojo.byId("rfqDetailsIdTextArea").style.visibility = "hidden";
				dojo.byId("rfqDetailsIdTextArea").style.display = "none";	
	} else {
		  dojo.byId("rfqDetailsIdText").style.visibility = "visible";
			dojo.byId("rfqDetailsIdText").style.display = "block";
			  dojo.byId("rfqDetailsIdTextArea").style.visibility = "visible";
				dojo.byId("rfqDetailsIdTextArea").style.display = "block";	
	}

	// Make RFQ form visible
	rfqFormP2.style.visibility = "visible";
	rfqFormP2.style.display = "block";

	// Change focus to that business so the form becomes visible to the user.
	window.location.href = "#biz" + businessId;

	// Set focus to text field. (Doesn't work in IE?)
	var nf = dojo.byId("name");
	nf.focus();

}

function onRequestQuoteContinueToQuestions() {

	var childClasses = getSelectedChildClasses();
	var totalChoices = getTotalChildClasses();

	// Validate RFQ Page 1.
	if (totalChoices.length != 0 && childClasses.length == 0) {
		var err = dojo.byId("rfqFormP1Error");
		err.innerHTML = "Please select at least one category that you are interested in.";
		return;
	} 
	var childIndustries = dojo.byId("businessChildIndustries");
	var children = childIndustries.getElementsByTagName("input");
	var childClassId = null;
	for ( var i = 0; i < children.length; i++) {
		var child = children[i];
		if (child.checked == true) {
			childClassId = child.value;
		} 
	}
	
	businessId = dojo.byId("businessId").value;
				
	var parentClassId = dojo.byId("parentIndustry").value;
	// XHR call to fetch the child categories.
	var reqData = {
		"parentClassId" :parentClassId,
		"childClassId" :childClassId
	};

	var busyIcon = document.getElementById("retrieveQnA");
	busyIcon.style.visibility = "visible";
	busyIcon.style.display = "inline";
	
	dojo.rawXhrPost( {
		url :"/api/lookup/getQuestionForBusinesss",

		headers : {
			"Content-Type" :"application/json"
		},

		postData :dojo.toJson(reqData),

		handleAs :"json",

		// If success from server.
		load : function(data, ioArgs) {
			  var d = document.getElementById('questionAnswersDiv');
			  var olddiv = document.getElementById('questionAnswersTable');
			  if(olddiv != null){
			  	d.removeChild(olddiv);
			  }	
			createQnAForm(data, businessId);
		},

		// If error from server.
		error : function(data, ioArgs) {
			// Hide busy icon.		
	}

	});
		
	busyIcon.style.visibility = "hidden";
	busyIcon.style.display = "none";
	
	// Change focus to that business so the form becomes visible to the user.
	window.location.href = "#biz" + businessId;

}

function makeNewFormVisible()
{    
  	//Hide All forms
	hideRFQForms();
  	
  	// Attach RFQ form page 2 under correct parent node
	var rfqFormP2 = dojo.byId('rfqFormP3');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(rfqFormP2);
	
	// Make RFQ form visible
	rfqFormP2.style.visibility = "visible";
	rfqFormP2.style.display = "block";
	
}

function createQnAForm (data, businessId){
	document.getElementById("questionExist").value = data["status"];

	if (document.getElementById("questionExist").value == "true") {
		//Clearing any old table of questions if present
		  var d = document.getElementById('questionAnswersDiv');
		  var olddiv = document.getElementById('questionAnswersTable');
		  if(olddiv != null){
		  	d.removeChild(olddiv);

		  	
		  }	
   //Make the question answer form visible
    makeNewFormVisible();
		  
	var status = data["status"];	
	var class_id = data["classificationId"];
	
	var quesDetailsArray = data["questionDetails"];
	var optDetailsArray = data["optionDetails"];
	var div = document.getElementById("questionAnswersDiv");
	 var tableElement = document.createElement("table");
	 tableElement.setAttribute('id','questionAnswersTable');
	 div.appendChild(tableElement);

	var rowCount
	for(var i = 0;i<quesDetailsArray.length ;i++ ){
	// Create Qn A form
		
	rowCount = tableElement.getElementsByTagName('tr').length;
	var newRow = tableElement.insertRow(rowCount);
	cell = newRow.insertCell(0);
	cell.width = "60%"
	cell.vAlign = "top";
	cell.innerHTML = quesDetailsArray[i].qText;
	cell.style.fontWeight= "bold"; 
	cell.innerHTML = cell.innerHTML+'<input type="hidden" name="Ans'+(i+1)+'" id="Ans'+(i+1)+'"/>';
	cell.innerHTML = cell.innerHTML+'<input type="hidden" name="Ques'+(i+1)+'Type" id="Ques'+(i+1)+'Type" value="'+quesDetailsArray[i].qType+'"/>';
	cell.innerHTML = cell.innerHTML+'<input type="hidden" id="questionExists" name="questionExists" value="'+status+'"/>';
	cell.innerHTML = cell.innerHTML+'<input type="hidden" id="classificationId" name="classificationId" value="'+class_id+'"/>';
	
	
	cell.align = "left";
	if(quesDetailsArray[i].qType == "FREEFORM"){
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.vAlign = "top";
		cell.innerHTML = '<textarea id="Question'+(i+1)+'" style="width: 250px" rows="4"></textarea>';	
		cell.align = "left";
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.innerHTML ='<div style="clear: both; font-size: 10pt; font-weight: bold;" id="errorMessage2'+(i+1)+'" class="errMsg"></div>';
		cell.align = "left";
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.innerHTML = "&nbsp;";
		
	} 
	else if (quesDetailsArray[i].qType == "DROPDOWN"){
		
		rowCount = tableElement.getElementsByTagName('tr').length;	
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.vAlign = "top";
		cell.innerHTML = '<select name="DropDown" id="Question'+(i+1)+'">';
		var optDef = document.createElement("option");
		document.getElementById("Question"+(i+1)).options.add(optDef); 
		optDef.text = "Select one option";
		optDef.value = "Default";
		
		for(var j = 0;j<optDetailsArray.length ;j++ ){	
			if(optDetailsArray[j].questionId == quesDetailsArray[i].questionId){				
				var opt = document.createElement("option");
		        // Add an Option object to Drop Down/List Box
		        // Assign text and value to Option object
		        document.getElementById("Question"+(i+1)).options.add(opt); 
		        opt.text = optDetailsArray[j].ansText;
		        opt.value = optDetailsArray[j].answerId;

				}
			} 
			
		cell.innerHTML=cell.innerHTML + "</select></td></tr>";
		cell.align = "left";
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.innerHTML ='<div style="clear: both; font-size: 10pt; font-weight: bold;" id="errorMessage2'+(i+1)+'" class="errMsg"></div>';		
		cell.align = "left";	
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.innerHTML = "&nbsp;";
		
	} else if (quesDetailsArray[i].qType == "RADIOBTN"){
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.vAlign = "top";
		for(var k = 0;k<optDetailsArray.length ;k++ ){			
			if(optDetailsArray[k].questionId == quesDetailsArray[i].questionId){
//
				cell.innerHTML = cell.innerHTML + '<input type="radio" name ="radioQues'+(i+1)+'" id="radioQues'+(i+1)+'" value="'+optDetailsArray[k].answerId+'">';
				cell.innerHTML=cell.innerHTML + optDetailsArray[k].ansText;
				cell.innerHTML=cell.innerHTML +'<br/>';
				}
			} 
		cell.align = "left";
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.innerHTML ='<div style="clear: both; font-size: 10pt; font-weight: bold;" id="errorMessage2'+(i+1)+'" class="errMsg"></div>';
		cell.align = "left";
		rowCount = tableElement.getElementsByTagName('tr').length;
		newRow = tableElement.insertRow(rowCount);
		cell = newRow.insertCell(0);
		cell.innerHTML = "&nbsp;";
	}
	cell.align = "left";
	}
	rowCount = tableElement.getElementsByTagName('tr').length;
	newRow = tableElement.insertRow(rowCount);
	cell = newRow.insertCell(0);
	cell.innerHTML = "&nbsp;"
	rowCount = tableElement.getElementsByTagName('tr').length;
	newRow = tableElement.insertRow(rowCount);
	cell = newRow.insertCell(0);
	 cell.align = "center";
	 cell.innerHTML ='<img id="busyQnA" class="busyIcon" src="/s/images/busyIcon.gif" />';
	 cell.innerHTML =cell.innerHTML+'<button type="button" id="buttonSubmitRFQ" name="submitButton" onclick="goToRfqForm();">'+"Next &gt;&gt; "+'</button>';
	 cell.innerHTML =cell.innerHTML+'<img height="1" width="1" border="0" src="http://bidsystem.adknowledge.com/conversion.php?cid=7e73c456-0dcc-4514-8abd-1bb2dbef969f">';
	rowCount = tableElement.getElementsByTagName('tr').length;
	newRow = tableElement.insertRow(rowCount);
	cell = newRow.insertCell(0);
	cell.innerHTML = cell.innerHTML+'<input type="hidden" id="questionCount" name="questionCount" value="'+(i)+'"/>';
	
	cell.align = "left";

	} else {
		
		onRequestQuoteContinue();
		
	}
}	

//
// User submits the RFQ
//
function submitDialog() {

	var errMsg = dojo.byId("errorMessage");
	errMsg.innerHTML = "";

	//
	// Data binding
	//
	var countryDropDown = dojo.byId("country");
	var selectedKey = countryDropDown.options[countryDropDown.selectedIndex].value;

	var multiple = dojo.byId("multiple").value;

	var parentIndustry = dojo.byId("parentIndustry");
	var selectedClasses = getSelectedChildClasses();

	var code = dojo.byId("code");
	var countryCode = getCodeForCountry(selectedKey);

	var phone = countryCode + dojo.byId("phone").value;

	// We fetch the raw phone number for length validation
	var rawPhone = dojo.byId("phone").value;

	// Remove all the special characters from the phone
	rawPhone = rawPhone.replace(/\D/g, '');

	// Bind request data.
	var reqData;

	if(dojo.byId("questionExist").value == true || dojo.byId("questionExist").value == "true" ) { 
		  var ans1Q = null;
		  var ans2Q = null;
		  var ans3Q = null;
		  var classId = null;
		  if(dojo.byId("questionCount").value == 1){
				ans1Q = dojo.byId("Ans1").value;
				classId = dojo.byId("classificationId").value;
		  } 

		  if(dojo.byId("questionCount").value == 2){
				ans1Q = dojo.byId("Ans1").value;
				ans2Q = dojo.byId("Ans2").value;
				classId = dojo.byId("classificationId").value;
		  }

		  if(dojo.byId("questionCount").value == 3){
				ans1Q = dojo.byId("Ans1").value;
				ans2Q = dojo.byId("Ans2").value;
				ans3Q = dojo.byId("Ans3").value;
				classId = dojo.byId("classificationId").value;
			}  	
	
	 reqData = {
		"businessId" :dojo.byId("businessId").value,
		"name" :dojo.byId("name").value,
		"businessName" :dojo.byId("businessName").value,
		"city" :dojo.byId("city").value,
		"state" :dojo.byId("state").value,
		"country" :selectedKey,
		"fromEmail" :dojo.byId("email").value,
		"fromPhone" :phone,
		"rawPhone" :rawPhone,
		"message" :dojo.byId("message").value,
		"multiple" :multiple,
		"parentClass" :parentIndustry.value,
		"childClasses" :selectedClasses,
	     "classificationId" :classId,
	     "ans1":ans1Q,
	     "ans2":ans2Q,
	     "ans3":ans3Q,
	     "questionCount":dojo.byId("questionCount").value
	};
	
	} else {
		 reqData = {
				"businessId" :dojo.byId("businessId").value,
				"name" :dojo.byId("name").value,
				"businessName" :dojo.byId("businessName").value,
				"city" :dojo.byId("city").value,
				"state" :dojo.byId("state").value,
				"country" :selectedKey,
				"fromEmail" :dojo.byId("email").value,
				"fromPhone" :phone,
				"rawPhone" :rawPhone,
				"message" :dojo.byId("message").value,
				"multiple" :multiple,
				"parentClass" :parentIndustry.value,
				"childClasses" :selectedClasses,
				"questionCount":0
			};
	}

	// Validate Input
	if (!validateInput(reqData)) {
		return;
	}

	// Activate busy icon.
	var busyIcon = dojo.byId("busy");
	busyIcon.style.visibility = "visible";
	busyIcon.style.display = "inline";

	// AJAX submit of RFQ.
	dojo.rawXhrPost( {

		url :"/api/business/submitRequestQuoteForBiz",

		headers : {
			"Content-Type" :"application/json"
		},

		postData :dojo.toJson(reqData),
		handleAs :"json",

		// If HTTP success.
		load : function(data, ioArgs) {
			if (data.respCode == 1) {
				// Success response from server.
				reqData["userId"] = data.userId;
		handleQuoteResponse(data, reqData);
		return;
	} else {
		// Hide busy icon.
		busyIcon = dojo.byId("busy");
		busyIcon.style.visibility = "hidden";

		var errDiv = dojo.byId("errorMessage");
		errDiv.innerHTML = data.respMsg;
		return;
	}
},

// If HTTP error.
		error : function(data, ioArgs) {
			// Hide busy icon.
		busyIcon = dojo.byId("busy");
		busyIcon.style.visibility = "hidden";

		var errDiv = dojo.byId("errorMessage");
		errDiv.innerHTML = "Oops! Unable to reach the server or server error.";
		return;
	}
	});

}

/**
 * Method to show the Thank you message after success from server after
 * submitting RFQ
 */
function handleQuoteResponse(data, reqData) {
	reqData = reqData;

	dojo
			.rawXhrPost( {
				url :"/api/business/renderRFQSuccess",

				headers : {
					"Content-Type" :"application/json"
				},

				postData :dojo.toJson(reqData),
				handleAs :"text",

				// If HTTP success.
				load : function(data, ioArgs) {

					// Hide busy icon.
				var busyIcon = dojo.byId("busy");
				busyIcon.style.visibility = "hidden";
				busyIcon.style.display = "none";

				// Hide the RFQ form.
				var rfqFormP2 = dojo.byId('rfqFormP2');
				rfqFormP2.style.display = "none";
				rfqFormP2.style.visibility = "hidden";

				// Display the data from the server to the user
				var tuDialog = dojo.byId("tuDialog");
				tuDialog.innerHTML = data;
				tuDialog.style.display = "block";
				tuDialog.style.visibility = "visible";
				
				var txtBusinessProfilePage = dojo.byId("txtBusinessProfilePage");
				if(txtBusinessProfilePage != undefined) {
					var divGlobalThankYouBox = dojo.byId("divGlobalThankYouBox");
					divGlobalThankYouBox.style.width = "590px";
				}

				// Attach the "Thank You" Or "PDF" dialog under the correct
				// business.
				var hd = dojo.byId('hd' + dojo.byId("businessId").value);
				hd.appendChild(tuDialog);
				return true;

			},

			// If HTTP error.
				error : function(data, ioArgs) {
					// Hide busy icon.
					var busyIcon = dojo.byId("busy");
					busyIcon.style.visibility = "hidden";

					var errDiv = dojo.byId("errorMessage");
					errDiv.innerHTML = "Oops! Unable to reach the server or server error.";
					return;
				}
			});
	return false;
}

/**
 * Invoked when a particular whitepaper is clicked by the user. Method displays
 * an input Form for the whitepapers.
 */
function showPopupForWhitepapers(rfqWhitepaperId) {
	var businessId = dojo.byId("businessId").value;
	dojo.byId('rfqWhitepaperId').value = rfqWhitepaperId;

	// Hide the Thank you form.
	var tuDialog = dojo.byId('tuDialog');
	tuDialog.style.display = "none";
	tuDialog.style.visibility = "hidden";

	// Show the Whitepaper Input Form
	var divWhitepaperSubmit = dojo.byId("divWhitepaperSubmit");
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(divWhitepaperSubmit);
	divWhitepaperSubmit.style.visibility = "visible";
	divWhitepaperSubmit.style.display = "block";

	return false;
}

/**
 * Invoked when user submits the whitepaper form.
 */
function submitWhitepaperForm() {
	// validate the whitepaper form
	var jobFunctionDD = dojo.byId('jobFunction');
	var jobFunction = jobFunctionDD.options[jobFunctionDD.selectedIndex].value;

	var companySizeDD = dojo.byId('companySize');
	var companySize = companySizeDD.options[companySizeDD.selectedIndex].value;

	var companyAddress = dojo.byId('companyAddress').value;
	var rfqWhitepaperId = dojo.byId('rfqWhitepaperId').value;

	var countryDropDown = dojo.byId("country");
	var selectedKey = countryDropDown.options[countryDropDown.selectedIndex].value;
	var code = dojo.byId("code");
	var countryCode = getCodeForCountry(selectedKey);
	var phone = countryCode + dojo.byId("phone").value;

	var fullName = dojo.byId("name").value;
	var businessName = dojo.byId("businessName").value;
	var city = dojo.byId("city").value;
	var state = dojo.byId("state").value;
	var country = selectedKey;
	var fromEmail = dojo.byId("email").value;
	var fromPhone = phone;

	var errorMessageForWhitepaper = dojo.byId("errorMessageForWhitepaper");
	if (jobFunction == '') {
		errorMessageForWhitepaper.innerHTML = "Enter Job Function";
		return false;
	}
	if (companySize == '') {
		errorMessageForWhitepaper.innerHTML = "Enter Company Size";
		return false;
	}
	if (companyAddress == '') {
		errorMessageForWhitepaper.innerHTML = "Enter Postal Code";
		return false;
	}

	var businessId = dojo.byId("businessId").value;

	// form has been validated so we can continue with the insert
	// cook the JSON object and send it to the server
	var postWhitepaperParams = {
		"rfqWhitepaperId" :rfqWhitepaperId,
		"fullName" :fullName,
		"businessName" :businessName,
		"city" :city,
		"state" :state,
		"country" :country,
		"email" :fromEmail,
		"phone" :fromPhone,
		"jobFunction" :jobFunction,
		"companySize" :companySize,
		"companyAddress" :companyAddress
	};

	// Show busy icon.
	var busyWhitepaper = dojo.byId("busyWhitepaper");
	busyWhitepaper.style.visibility = "visible";
	busyWhitepaper.style.display = "inline";

	dojo
			.rawXhrPost( {
				url :"/api/business/submitPostRFQResponse",
				headers : {
					"Content-Type" :"application/json"
				},
				postData :dojo.toJson(postWhitepaperParams),
				handleAs :"text",
				// If success from server.
				load : function(data, ioArgs) {
					// alert(data);

				// Hide busy icon.
				var busyWhitepaper = dojo.byId("busyWhitepaper");
				busyWhitepaper.style.visibility = "hidden";
				busyWhitepaper.style.display = "none";

				var divWhitepaperSubmit = dojo.byId("divWhitepaperSubmit");
				divWhitepaperSubmit.innerHTML = data;
				var hd = dojo.byId('hd' + businessId);
				hd.appendChild(divWhitepaperSubmit);
				divWhitepaperSubmit.style.visibility = "visible";
				divWhitepaperSubmit.style.display = "block";

				// force download the whitepaper
				/*
				 * var txtWhitepaperHiddenId =
				 * dojo.byId("txtWhitepaperHiddenId").value;
				 * if(txtWhitepaperHiddenId != '') {
				 * window.location.href="/web/resource/whitepaperDownload/"+txtWhitepaperHiddenId; }
				 */
			},
			// If error from server.
				error : function(data, ioArgs) {
					// Hide busy icon.
				var busyWhitepaper = dojo.byId("busyWhitepaper");
				busyWhitepaper.style.visibility = "hidden";
				busyWhitepaper.style.display = "none";

				var errorMessageForWhitepaper = dojo
						.byId("errorMessageForWhitepaper");
				errorMessageForWhitepaper.innerHTML = "Error occoured .. Please try again";
				return;
			}
			});
	return false;
}

function resetRFQForm() {
	dojo.byId("businessId").value = "";
	// dojo.byId("name").value = "";
	// dojo.byId("businessName").value = "";
	// dojo.byId("city").value = "";
	// dojo.byId("state").value = "";
	// dojo.byId("email").value = "";
	// dojo.byId("phone").value = "";
	dojo.byId("message").value = "";
	dojo.byId("errorMessage").innerHTML = "";

	dojo.byId("rfqFormP1Error").innerHTML = "";
	dojo.byId("businessChildIndustries").innerHTML = "";

	dojo.byId("interestedIn").innerHTML = "";

}

function hideRFQForms() {
	var rfqFormP1 = dojo.byId('rfqFormP1');
	rfqFormP1.style.visibility = "hidden";
	rfqFormP1.style.display = "none";

	var rfqFormP2 = dojo.byId('rfqFormP2');
	rfqFormP2.style.visibility = "hidden";
	rfqFormP2.style.display = "none";
	
	var rfqFormP3 = dojo.byId('rfqFormP3');
	rfqFormP3.style.visibility = "hidden";
	rfqFormP3.style.display = "none";
	var tuDialog = dojo.byId('tuDialog');
	tuDialog.style.visibility = "hidden";
	tuDialog.style.display = "none";

}



function hideRecommendationForm() {
	var submitRecommendationDialog = dojo.byId('submitRecommendationDialog');
	if (submitRecommendationDialog != null) {
		submitRecommendationDialog.style.visibility = "hidden";
		submitRecommendationDialog.style.display = "none";
	}
}

/**
 * Get array of selected child industries.
 */
function getSelectedChildClasses() {

	var childIndustries = dojo.byId("businessChildIndustries");
	var children = childIndustries.getElementsByTagName("input");
	var selectedClasses = new Array();

	for ( var i = 0; i < children.length; i++) {
		var child = children[i];
		if (child.checked == true) {
			selectedClasses.push(child.value);
		}
	}

	return selectedClasses;

}

/**
 * Get array of All the child industries.
 */
function getTotalChildClasses() {

	var childIndustries = dojo.byId("businessChildIndustries");
	var children = childIndustries.getElementsByTagName("input");
	var totalClasses = new Array();

	for ( var i = 0; i < children.length; i++) {
		var child = children[i];
		totalClasses.push(child.value);
	}

	return totalClasses;

}

function validateInput(reqData) {
	var errDiv = dojo.byId("errorMessage");

	if (dojo.string.trim(reqData.name).length == 0) {
		errDiv.innerHTML = "Full Name is required.";
		return false;
	} else if (!isLengthValid(dojo.string.trim(reqData.name), "5", "30")) {
		errDiv.innerHTML = "Invalid Full Name. Please Re-enter Your Full Name.";
		return false;
	} else if (!nameValidator(dojo.string.trim(reqData.name))) {
		errDiv.innerHTML = "Invalid Full Name. Please Re-enter Your Full Name.";
		return false;
	}

	if (dojo.string.trim(reqData.businessName).length == 0) {
		errDiv.innerHTML = "Company Name is required. ";
		return false;
	} else if (!isLengthValid(dojo.string.trim(reqData.businessName), "3", "80")) {
		errDiv.innerHTML = "Invalid Company Name. Please Re-Enter Your Company Name. ";
		return false;
	}

	if (dojo.string.trim(reqData.city).length == 0) {
		errDiv.innerHTML = "City is required.";
		return false;
	} else if (!isLengthValid(dojo.string.trim(reqData.city), "2", "60")) {
		errDiv.innerHTML = "Invalid City. Please Re-enter Your City.";
		return false;
	} else if (!IsValidCity(dojo.string.trim(reqData.city))) {
		errDiv.innerHTML = "Invalid City. Please Re-enter Your City.";
		return false;
	}

	if (dojo.string.trim(reqData.state).length == 0) {
		errDiv.innerHTML = "State/Province is required.";
		return false;
	} else if (!isLengthValid(dojo.string.trim(reqData.state), "2", "60")) {
		errDiv.innerHTML = "Invalid State/Province. Please Re-enter Your State/Province.";
		return false;
	} else if (!IsValidCity(dojo.string.trim(reqData.state))) {
		errDiv.innerHTML = "Invalid State/Province. Please Re-enter Your State/Province.";
		return false;
	}

	if (dojo.string.trim(reqData.country).length == 0) {
		errDiv.innerHTML = "Country is required.";
		return false;
	}

	if (dojo.string.trim(reqData.fromEmail).length == 0) {
		errDiv.innerHTML = "Email address is required.";
		return false;
	} else if (!isLengthValid(dojo.string.trim(reqData.fromEmail), "6", "128")) {
		errDiv.innerHTML = "Invalid Email. Please Enter a Valid Email Address.";
		return false;
	} else if (!isValidEmail(dojo.string.trim(reqData.fromEmail))) {
		errDiv.innerHTML = "Invalid Email. Please Enter a Valid Email Address.";
		return false;
	}

	if (dojo.string.trim(reqData.fromPhone).length == 0) {
		errDiv.innerHTML = "Phone is required.";
		return false;
	} else if (!isLengthValid(dojo.string.trim(reqData.rawPhone), "9", "20")) {
		errDiv.innerHTML = "Invalid Phone Number. Please Re-enter Your Phone Number.";
		return false;
	} else if (!IsPhoneValid(dojo.string.trim(reqData.fromPhone))) {
		errDiv.innerHTML = "Invalid Phone Number. Please Re-enter Your Phone Number.";
		return false;
	}
	
	//check if the Q n A form was filled so as to disable RFQ details accordingly
	if(dojo.byId("questionExist").value=="true" || dojo.byId("questionExist").value==true){
		
	} else {
		//
		if (dojo.string.trim(reqData.message).length == 0) {
			errDiv.innerHTML = "Requirements are required.";
			return false;
		} else if (!isLengthValid(dojo.string.trim(reqData.message), "20", "1500")) {
			errDiv.innerHTML = "Invalid Requirements. Please Enter Valid Requirements.";
			return false;
		}
	}



	return true;
}

function nameValidator(sText) {
	if (sText.indexOf(" ") < 0)
		return false;
	else
		return true;
}

function isValidEmail(email) {
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailPattern.test(email);
}

function allValidChars(email) {
	var parsed = true;
	var countAmpersand = 0;
	var validchars = "abcdefghijklmnopqrstuvwxyz0123456789.-_";
	for ( var i = 0; i < email.length; i++) {
		var letter = email.charAt(i).toLowerCase();
		if (letter == "@") {
			countAmpersand = countAmpersand + 1;

		}
		if (countAmpersand > 1) {
			parsed = false;
			break;
		}
		if (validchars.indexOf(letter) != -1 || countAmpersand > 0)
			continue;
		parsed = false;
		break;
	}
	return parsed;
}

function IsValidCity(sText) {
	var ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-.,"
			+ " ";
	var IsString = true;
	var Char;

	for (i = 0; i < sText.length && IsString == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsString = false;
		}
	}
	return IsString;

}

function IsAlphaNumeric(sText) {

	var ValidChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789."
			+ " ";
	var IsString = true;
	var Char;

	for (i = 0; i < sText.length && IsString == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsString = false;
		}
	}
	return IsString;

}

function IsPhoneValid(sText) {
  if (sText.indexOf("+") == 0)
	sText = sText.slice(1);	
  var ValidChars = "1234567890().-,";
  var specialChars = "().-,";
  var IsString = true;
  var Char;
  // if(sText.indexOf("+") > 1)
  // {
  // IsString = false;
  // return IsString;
  // }
  for (i = 0; i < sText.length && IsString == true; i++) {
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) == -1) {
      IsString = false;
    }
  }
  
  for (i = 0; i+4 < sText.length && IsString == true; i++) {
    Char = sText.charAt(i);
    if ( specialChars.indexOf(Char) >= 0 )
	    continue;
    value = parseInt(Char);
    nextChar = sText.charAt(i+1);
    if ( specialChars.indexOf(nextChar) >= 0 )
        continue;
    nextValue = parseInt(nextChar);
    diff = nextValue-value;
    if ( ( diff > -9 && diff < -1 ) || ( diff > 1 && diff < 9 ) )
      continue;
    
    switch(diff+10) {
    case  1: change = 1; break;
    case  9: change = -1; break;
    case 10: change = 0; break;
    case 11: change = 1; break;
    case 19: change = -1; break;
    }

    for (j = i+2, k = 0 ; k < 3 ; j++, k++) {
      testValue = nextValue+change;
      
      if (testValue > 9) testValue = testValue - 10;
      if (testValue < 0) testValue = testValue + 10;
      Char = sText.charAt(j);
      if ( specialChars.indexOf(Char) >= 0 )
        break;
      value = parseInt(Char);
      if (value != testValue)
      break;
      nextValue = value;
    }
    
    if (k==3)
      IsString = false;
  }
  
  var phoneNum = dojo.byId("phone").value;
  phoneNum = dojo.string.trim(phoneNum);
  if (phoneNum.indexOf("0") == 0)
	  IsString = false;
  return IsString;
}


// Will check if all character from the pattern is present in text, if yes then
// will return true
function IsPresent(sText, pattern) {
	var ValidChars = pattern;
	var IsPresent = false;
	var Char;

	for (i = 0; i < sText.length && IsPresent == false; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) != -1) {
			IsPresent = true;
		}
	}
	return IsPresent;

}

function isLengthValid(sText, minLength, maxLength) {
	var lengthValid = false;
	if (parseInt(minLength) <= sText.length
			&& sText.length <= parseInt(maxLength)) {
		lengthValid = true;
	}
	return lengthValid;
}

function isLengthEqual(sText, maxLength) {
	var lengthValid = false;
	if (sText.length == parseInt(maxLength)) {
		lengthValid = true;
	}
	return lengthValid;
}

/*******************************************************************************
 * Business Profile Related
 ******************************************************************************/
function showProfile(id, name) {

	// Hide dialogs.
	hideAllDialogs();

	// Show bizProfile
	var bizInfDlg = dojo.byId('bizProfileDialog');
	var hd = dojo.byId('hd' + id);
	hd.appendChild(bizInfDlg);
	clearProfileDialog();
	bizInfDlg.style.display = "block";
	bizInfDlg.style.visibility = "visible";

	window.location.href = "#biz" + id;

	// Activate busy icon.
	var busyIcon = dojo.byId("icnBizInfBusy");
	busyIcon.style.visibility = "visible";

	// Fetch profile from server.
	var reqData = {
		"businessId" :id
	};

	dojo.rawXhrPost( {
		url :"/api/business/fetchProfile",

		headers : {
			"Content-Type" :"application/json"
		},

		postData :dojo.toJson(reqData),

		handleAs :"json",

		// If success from server.
		load : function(data, ioArgs) {
			fetchedBizProfile(data);
		},

		// If error from server.
		error : function(data, ioArgs) {
			// Hide busy icon.
		var busyIcon = dojo.byId("icnBizInfBusy");
		busyIcon.style.visibility = "hidden";
		alert(data);
	}

	});
}

function fetchedBizProfile(ret) {

	// Hide busy icon.
	var busyIcon = dojo.byId("icnBizInfBusy");
	busyIcon.style.visibility = "hidden";

	if (ret.respCode != "1") {
		clearProfileDialog();
		dlgItem = dojo.byId("valDesc");
		dlgItem.innerHTML = ret.respMsg;
		return;
	}

	// Populate the profile dialog box.
	dlgItem = dojo.byId("valBizName");
	dlgItem.innerHTML = ret.business.businessName + ". "
			+ ret.business.cityName + ", " + ret.business.countryName;

	dlgItem = dojo.byId("valWeb");
	dlgItem.innerHTML = "<a href=\"" + ret.business.website
			+ "\" target=\"_blank\">" + ret.business.website + "</a>";

	dlgItem = dojo.byId("valDesc");
	dlgItem.innerHTML = ret.business.description;

	dlgItem = dojo.byId("valCat");
	dlgItem.innerHTML = ret.business.pName + ": ";

	text = "";
	count = 0;

	if (ret.business.c1Name.length > 0) {
		text += (count == 0) ? "" : ", ";
		count++;
		text += ret.business.c1Name;
	}
	if (ret.business.c2Name.length > 0) {
		text += (count == 0) ? "" : ", ";
		count++;
		text += ret.business.c2Name;
	}
	if (ret.business.c3Name.length > 0) {
		text += (count == 0) ? "" : ", ";
		count++;
		text += ret.business.c3Name;
	}
	if (ret.business.c4Name.length > 0) {
		text += (count == 0) ? "" : ", ";
		count++;
		text += ret.business.c4Name;
	}
	if (ret.business.c5Name.length > 0) {
		text += (count == 0) ? "" : ", ";
		count++;
		text += ret.business.c5Name;
	}

	dlgItem = dojo.byId("valChildCat");
	dlgItem.innerHTML = text;

}

function clearProfileDialog() {

	// Clean-up dialog box
	dlgItem = dojo.byId("valBizName");
	dlgItem.innerHTML = "";

	dlgItem = dojo.byId("valDesc");
	dlgItem.innerHTML = "";

	dlgItem = dojo.byId("valWeb");
	dlgItem.innerHTML = "";

	dlgItem = dojo.byId("valCat");
	dlgItem.innerHTML = "";

	dlgItem = dojo.byId("valChildCat");
	dlgItem.innerHTML = "";

}

function hideBizInf() {
	// Hide busy icon.
	var busyIcon = dojo.byId("icnBizInfBusy");
	busyIcon.style.visibility = "hidden";

	// Hide dialog
	var bizInfDlg = dojo.byId('bizProfileDialog');
	bizInfDlg.style.visibility = "hidden";
	bizInfDlg.style.display = "none";

}

/*******************************************************************************
 * "Connect" Dialog Related
 ******************************************************************************/

/**
 * When user clicks on the "connect" link for any search result, and this is a
 * logged-in user having a business profile.
 */
function onConnectClick(businessId, businessName) {

	// Hide all other dialogs.
	hideAllDialogs();

	var checkConnect = dojo.byId('checkConnection');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(checkConnect);

	checkConnect.style.display = "block";
	checkConnect.style.visibility = "visible";

	var busyIcon = dojo.byId('busycheckConnections');
	busyIcon.style.visibility = "visible";

	var errMsg = dojo.byId('checkConnectionError');
	errMsg.innerHTML = "";

	var reqData = {
		"businessId" :businessId,
		"businessName" :businessName
	};

	dojo.rawXhrPost( {
		url :"/api/connections/checkConnection",

		headers : {
			"Content-Type" :"application/json"
		},

		postData :dojo.toJson(reqData),

		handleAs :"json",

		// If success from server.
		load : function(data, ioArgs) {
			checkConnectRespHandle(data, businessId, businessName);
			return;
		},

		// If error from server.
		error : function(data, ioArgs) {
			alert(data);
		}

	});
}

/**
 * continue connect operation after a successful connection possiblity
 */
function onConnectClickCont(businessId, businessName) {

	// Hide all other dialogs.
	hideAllDialogs();

	// Stick the connect div under this business result.
	var connectDlg = dojo.byId('connectDlg');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(connectDlg);
	clearConnectDialog();

	var connectTitle = dojo.byId("connectTitle");
	connectTitle.innerHTML = "Invite " + businessName
			+ " to join your business network";

	var connectRelLabel = dojo.byId("connectRelLabel");
	connectRelLabel.innerHTML = "What is your company's relationship with "
			+ businessName + "?";

	dojo.byId("targetBusinessId").value = businessId;

	// Show the "connect" dialog.
	connectDlg.style.display = "block";
	connectDlg.style.visibility = "visible";

	window.location.href = "#hd" + businessId;
	window.location.href = "#biz" + businessId;
}

/**
 * When user clicks on the "connect" link for any search result, but this is not
 * a logged-in user or user does not have a business profile.
 */
function onUnsupportedConnectClick(businessId, businessName) {

	// Hide all other dialogs.
	hideAllDialogs();

	// Stick the connect div under this business result.
	var connectDlg = dojo.byId('connectDlg');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(connectDlg);

	// Show the "connect" dialog.
	connectDlg.style.display = "block";
	connectDlg.style.visibility = "visible";

	window.location.href = "#hd" + businessId;
	window.location.href = "#biz" + businessId;

}

function clearConnectDialog() {

	// Reset the "relationship" radio buttons.
	var container = dojo.byId("connectRelationships");
	var children = container.getElementsByTagName("input");

	for ( var i = 0; i < children.length; i++) {
		children[i].checked = false;
	}

	// Clear the custom message.
	var connectMsg = dojo.byId("connectMsg");
	connectMsg.value = "";

	// Clear error messages.
	var errRelationship = dojo.byId("errRelationship");
	errRelationship.innerHTML = "";

}

function hideCheckConnection() {

	var checkConnect = dojo.byId('checkConnection');
	checkConnect.style.visibility = "hidden";
	checkConnect.style.display = "none";
}

function hideConnectDialog() {

	var connectDlg = dojo.byId('connectDlg');
	connectDlg.style.visibility = "hidden";
	connectDlg.style.display = "none";
	hideCheckConnection();
}

function hideConnectAckDialog() {
	var connectDlg = dojo.byId('connectAckDialog');
	connectDlg.style.visibility = "hidden";
	connectDlg.style.display = "none";
}

function hideAllDialogs() {

	hideRFQForms();
	hideBizInf();
	hideCheckConnection();
	hideConnectDialog();
	hideConnectAckDialog();
	clearContent();
	// hideLocalSearchFilter();
	hideRecommendationForm();
}

/**
 * When user submits the "connect" form.
 */
function submitConnectForm() {

	//
	// Validation
	//
	var errRelationship = dojo.byId("errRelationship");
	errRelationship.innerHTML = "";

	// Relationship chosen?
	var relationship = getChosenRelationship();

	if (relationship == -1) {
		// Flag error.
		errRelationship.innerHTML = "Please select your relationship.";
		return;
	}

	var message = dojo.byId("connectMsg").value;
	var businessId = dojo.byId("targetBusinessId").value;

	//
	// XHR to the server.
	//

	// Busy Icon
	var busyIcon = dojo.byId("iconConnectBusy");
	busyIcon.style.visibility = "visible";

	var reqData = {
		"businessId" :businessId,
		"type" :relationship,
		"body" :message
	};

	dojo.rawXhrPost( {
		url :"/api/connections/connectRequest",

		headers : {
			"Content-Type" :"application/json"
		},

		postData :dojo.toJson(reqData),

		handleAs :"json",

		// If success from server.
		load : function(data, ioArgs) {
			busyIcon.style.visibility = "hidden";
			connectRespHandle(data, businessId);
		},

		// If error from server.
		error : function(data, ioArgs) {
			// Hide busy icon.
		busyIcon.style.visibility = "hidden";
		alert(data);
	}

	});

} // connectSubmit()

/**
 * Return the chosen relationship on the "connect" form. Return null, if user
 * has not chosen any relationship type.
 */
function getChosenRelationship() {

	var container = dojo.byId("connectRelationships");
	var children = container.getElementsByTagName("input");

	for ( var i = 0; i < children.length; i++) {
		if (children[i].checked) {
			return children[i].value;
		}
	}

	// None checked.
	return -1;

}

/**
 * Received a success response from server for a "connectRequest".
 */
function connectRespHandle(data, businessId) {

	// Hide dialogs
	hideAllDialogs();

	// Stick the ACK dialog in the correct position.
	var connectAckDlg = dojo.byId('connectAckDialog');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(connectAckDlg);

	if (data.respCode == 1) {
		// Successful
		dojo.byId("connectAckTitle").innerHTML = "Thank You";
		dojo.byId("connectAckMsg").innerHTML = "<p>Thank you for your connection request. Your request has been sent.</p>"
				+ "<p>TradeSeam connects customers, suppliers and service providers; all who have an interest in accelerating the growth of their business.</p>"
				+ "<p>Invite your contacts to join your business network on TradeSeam so that you can receive more sales referrals for your business.</p>"
				+ "<center><a href=\"/web/invite/inviteForm\"><img src=\"/s/images/getStartedNow.png\" alt=\"Get Started Now!\" border=\"0\" /></a></center>";
	} else {
		// Failed
		dojo.byId("connectAckTitle").innerHTML = "Oops!";
		dojo.byId("connectAckMsg").innerHTML = "We encountered the following error: <br/>"
				+ data.respMsg;
	}

	// Show the dialog
	var ackDialog = dojo.byId("connectAckDialog");
	ackDialog.style.display = "block";
	ackDialog.style.visibility = "visible";

} // connectRespHandle()

/**
 * Received a success response from server for a "checkConnectRequest".
 */
function checkConnectRespHandle(data, businessId, businessName) {

	// Hide dialogs
	hideAllDialogs();

	var checkConnect = dojo.byId('checkConnection');
	var hd = dojo.byId('hd' + businessId);
	hd.appendChild(checkConnect);

	if (data.respCode == 1) {
		// Successful
		var busyIcon = dojo.byId('busycheckConnections');
		busyIcon.style.visibility = "hidden";
		var errMsg = dojo.byId('checkConnectionError');
		errMsg.innerHTML = "";
		errMsg.style.visibility = "hidden";
		checkConnect.style.visibility = "hidden";
		checkConnect.style.display = "none";
		onConnectClickCont(businessId, data.businessName);
	} else {
		// Failed
		busyIcon = dojo.byId('busycheckConnections');
		busyIcon.style.visibility = "hidden";
		errMsg = dojo.byId('checkConnectionError');
		errMsg.innerHTML = data.respMsg;
		errMsg.style.visibility = "visible";
		checkConnect.style.display = "block";
		checkConnect.style.visibility = "visible";
	}
} // checkConnectRespHandle()

/**
 * show lcoal search filter
 * 
 * @return
 */
function showLocalSearchFilter() {
	// Hide dialogs
	// hideAllDialogs();

	var localSearch = dojo.byId("localSearch");
	localSearch.style.visibility = "visible";
	localSearch.style.display = "block";

	var filterLink = dojo.byId("filterLink");
	filterLink.innerHTML = "<a href=\"javascript:hideLocalSearchFilter()\">Hide</a>";
} // showLocalSearchFilter ()

/**
 * remove default text
 * 
 * @return
 */
function locationTextBoxClicked() {
	var inputBox = dojo.byId("location");
	if (inputBox != null && inputBox.value == "City, State")
		inputBox.value = "";
}

/**
 * hide local search filter
 * 
 * @return
 */
function hideLocalSearchFilter() {
	var localSearch = dojo.byId("localSearch");
	localSearch.style.visibility = "hidden";
	localSearch.style.display = "none";

	var filterLink = dojo.byId("filterLink");
	filterLink.innerHTML = "<a href=\"javascript:showLocalSearchFilter()\">Click here</a>";
} // hideLocalSearchFilter ()

/**
 * Method which fetches the country code for a country and places the value in a
 * div
 * 
 * @param countryId
 *            id of the country
 * @return
 */
function replaceCountryCode(countryId) {
	var countryCode = getCodeForCountry(countryId);
	var phoneCountryCode = dojo.byId("phoneCountryCode");
	phoneCountryCode.innerHTML = countryCode;
}

function goToRfqForm(){

	var questionCount = dojo.byId("questionCount").value;
	var errDiv;
	for(var j = 1;j <= questionCount;j++){
		errDiv = dojo.byId("errorMessage2"+j);
		errDiv.innerHTML="";
	}
	for(var i = 1;i <= questionCount;i++){
		if(document.getElementById("Ques"+i+"Type").value == "FREEFORM"){
			errDiv = dojo.byId("errorMessage2"+i);
			var ansVal = document.getElementById("Question"+i).value;
			document.getElementById("Ans"+i).value=dojo.string.trim(ansVal);
			
//			if(dojo.string.trim(ansVal).length == 0)	{
//				   errDiv.innerHTML = "Please enter the answer";
//				   document.getElementById("Question"+i).focus();
//				   return false;
//			}
		     if(dojo.string.trim(ansVal).length > 1024)  {
		           errDiv.innerHTML = "Please enter the answer within the maximum allowed range of 1024 characters";
		           document.getElementById("Question"+i).focus();
		           return false;
		     } 
//				  
		} else if(document.getElementById("Ques"+i+"Type").value == "DROPDOWN"){
			errDiv = dojo.byId("errorMessage2"+i);
			var dropDown = document.getElementById("Question"+i);
			var selectedValue = dropDown.options[dropDown.selectedIndex].value;
			document.getElementById("Ans"+i).value=selectedValue;			
			if(dojo.string.trim(selectedValue) == "Default"){
				   errDiv.innerHTML = "Please select the answer";
				   return false;
			}	  
		}	else if(document.getElementById("Ques"+i+"Type").value == "RADIOBTN"){
			errDiv = dojo.byId("errorMessage2"+i);
			var rad_val = null;
			var oRadio = document.rfqHtmlFormNew.elements["radioQues"+i];
			for (var k=0; k < oRadio.length; k++)
			   {
			   if (oRadio[k].checked)
			      {
			      rad_val = oRadio[k].value;
			      }
			   }

			   if(rad_val==null){
				   errDiv.innerHTML = "Please select the answer";
				  
				   return false;
			   }   

					document.getElementById("Ans"+i).value = rad_val; 
		} 
		}
		onRequestQuoteContinue();
		return true;
	}		

