/*
 * Returns an object that allows
 * us to make the requests.
 *
 * Author : Simon Vaillancourt
 */
function getRequest(){
	var http;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		http = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		http = new XMLHttpRequest();
	}
	return http;
}

function submitAsyncForm(confirmationPage){
	hideSubmitButton();
	var formId = document.getElementById('AsyncContent');
	var postStr= '';
	for (i = 0; i < formId.elements.length; i++) {
		formElem = formId.elements[i];
		if( formElem.name=='Client.PhoneCodeNumber' ){continue;}
		switch (formElem.type) {
		case 'text':
		case 'select-one':
		case 'hidden':
		case 'password':
		case 'textarea':
			postStr += formElem.name + '=' + escape(formElem.value) + '&';
			break;
		case 'checkbox':
		case 'radio':
			if(formElem.checked==true){
				postStr += formElem.name + '=' + escape(formElem.value) + '&';
			}
			break;
		}
	}

	var encoded = encode64(postStr);
	postStr += 'Client.Encoded=' + encoded;
	var http = getRequest();
	var url = '/cgi/en/cpgAsync.lead.save';
	http.open('POST',url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", postStr.length);
	http.setRequestHeader("Connection", "close");
	http.onreadystatechange = function handleResponse() {
		if(http.readyState == 4){
			var response = http.responseText;
			if( response == 'success' ){
				window.location = confirmationPage;
			}else{
				showSubmitButton();
				cleanup('FormAsyncContentFields');
				createHtml('FormAsyncContentFields', response);
				toggleStateProvince( 'main' );
				return false;
			}
		}
	}
	http.send(postStr);
	return false;
}
function hideSubmitButton(){
	document.getElementById('FormAsyncContentFields').style.display = 'none';
	document.getElementById('asyncFormSubmit').style.display = 'none';
	document.getElementById('asyncWaiting').style.display = 'block';
}
function showSubmitButton(){
	document.getElementById('FormAsyncContentFields').style.display = 'block';
	document.getElementById('asyncFormSubmit').style.display = 'block';
	document.getElementById('asyncWaiting').style.display = 'none';
}

function loadform(){
	insertGATrackingFromUrchin();
	var strHref = window.location.href;
	var strQueryString = strHref.split("?");
	var http = getRequest();
	var requestString = '/cgi/en/cpgAsync.lead.prep?'+unescape(strQueryString[1]);
	http.open('get', requestString);
	http.onreadystatechange = function handleResponse() {
		if(http.readyState == 4){
			var response = http.responseText;
			createHtml('FormAsyncContentFields', response);
			toggleStateProvince( 'main' );
		}
	}
	http.send(null);
}

function cleanup(elementId){
	var content = document.getElementById(elementId);
	var child = content.firstChild;
	while( child != null ){
		content.removeChild(child);
		child = content.firstChild;
	}
}

function createHtml(elementId, html){
	var content = document.getElementById(elementId);
	content.appendChild(toDOM(html));
}

function toDOM(HTMLstring){
	var d = document.createElement('div');
	d.innerHTML = HTMLstring.replace(/\r|\n|\r\n/g, "");
	var docFrag = document.createDocumentFragment();
	while (d.firstChild) {
		docFrag.appendChild(d.firstChild)
	};
	return docFrag;
}

function validateLegalAgreement() {
	if ( !document.getElementById('pubInterest').checked ) {
		alert("You need to agree to the Terms and Conditions before receiving bids.");
		return false;
	}
	return true;
}

/*
 * inserts GA tracking if it does not exists 
 * and if urchin parameters are passed in the
 * URL
 *
 * Author : Simon Vaillancourt
 *  
 */
function insertGATrackingFromUrchin() {
	var strHref = window.location.href;
	var strQueryString = strHref.split("?");
	var trackingSource = document.getElementById("GA_TrackingSource");
	var trackingMedium = document.getElementById("GA_TrackingMedium");
	var trackingTerm = document.getElementById("GA_TrackingTerm");
	var trackingContent = document.getElementById("GA_TrackingContent");
	var trackingCampaign = document.getElementById("GA_TrackingCampaign");

	var gaMap = new Object();
	gaMap.source="";
	gaMap.medium="";
	gaMap.term="";
	gaMap.content=""
		gaMap.campaign="";
	var array1 = strQueryString[1].split("&");
	for(var i = 0 ; i < array1.length ; i++ ){
		var array2 = array1[i].split("=");
		if(array2[0]=='utm_source'){gaMap.source=array2[1]}
		if(array2[0]=='utm_medium'){gaMap.medium=array2[1]}
		if(array2[0]=='utm_term'){gaMap.term=array2[1]}
		if(array2[0]=='utm_content'){gaMap.content=array2[1]}
		if(array2[0]=='utm_campaign'){gaMap.campaign=array2[1]}
	}

	if(trackingSource == null){
		createHtml('AsyncContent', '<input type="hidden" name="Client.ClientPortalRelations.ClientPortalRelation.GaTrackingSource" id="GA_TrackingSource" value="' + gaMap.source + '"/>');
	}
	if(trackingMedium == null){
		createHtml('AsyncContent', '<input type="hidden" name="Client.ClientPortalRelations.ClientPortalRelation.GaTrackingMedium" id="GA_TrackingMedium" value="' + gaMap.medium + '"/>');
	}
	if(trackingTerm == null){
		createHtml('AsyncContent', '<input type="hidden" name="Client.ClientPortalRelations.ClientPortalRelation.GaTrackingTerm" id="GA_TrackingTerm" value="' + gaMap.term + '"/>');
	}
	if(trackingContent == null){
		createHtml('AsyncContent', '<input type="hidden" name="Client.ClientPortalRelations.ClientPortalRelation.GaTrackingContent" id="GA_TrackingContent" value="' + gaMap.content + '"/>');
	}
	if(trackingCampaign == null){
		createHtml('AsyncContent', '<input type="hidden" name="Client.ClientPortalRelations.ClientPortalRelation.GaTrackingCampaign" id="GA_TrackingCampaign" value="' + gaMap.campaign + '"/>');
	}
}
