function httpRequest(url, requestType, requestParameters ) {	
	// creates XMLHttpRequest object
	if (window.XMLHttpRequest) req = new XMLHttpRequest();
	else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");    
	if ( requestType.toLowerCase() == "get" ) {        
		req.open("GET", url, false);
		req.send(null);
	}
	else {
		req.open("POST", url, false);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", requestParameters.length);
		req.setRequestHeader("Connection", "close");
		req.send(requestParameters);
	}
	return req.responseText;
}

function prevYears( currentPosition, yearsPerPage ) {
  var url = "/ajax/message_retriever.php";
  var urlParams = "action=prevYears&currentPosition=" + currentPosition + "&yearsPerPage=" + yearsPerPage; 
  result = httpRequest( url, "POST", urlParams );
  document.getElementById( "yearsContainer" ).innerHTML = result;
  //var responeObj = eval('(' + result + ')');  
}
function showMonths (currentYear){
	var url = "/ajax/message_retriever.php";
  var urlParams = "action=showMonths&currentYear=" + currentYear;
  result = httpRequest( url, "POST", urlParams );
  document.getElementById( "monthsContainer" ).innerHTML = result;
}
function showSubscriptionHistory (id){
	var url = "/ajax/message_retriever.php";
  var urlParams = "action=showHistory&id=" + id;
  result = httpRequest( url, "POST", urlParams );
  document.getElementById( "dashboardContainer" ).style.display = 'none';
  document.getElementById( 'subscription-history' ).style.display = 'block';
  document.getElementById( "subscription-history" ).innerHTML = result; 
}
function showArticle( articleId ) {
	var url = "/ajax/message_retriever.php";
	var urlParams = "action=showArticle&articleId=" + articleId;
	result = httpRequest( url, "POST", urlParams );
	document.getElementById( "dashboardContainer" ).style.display = 'none';
	document.getElementById( 'subscription-history' ).style.display = 'block';
	document.getElementById( "subscription-history" ).innerHTML = result; 
}
function showTwoArticle( articleId ) {
	var url = "/ajax/message_retriever.php";
	var urlParams = "action=showTwoArticle&articleId=" + articleId;
	result = httpRequest( url, "POST", urlParams );
	document.getElementById( "resource-center-container" ).style.display = 'none';
	document.getElementById( 'subscription-history' ).style.display = 'block';
	document.getElementById( "subscription-history" ).innerHTML = result; 
}
function showArticleFromMoreArticles( articleId ) {
	var url = "/ajax/message_retriever.php";
	var urlParams = "action=showArticleFromMoreArticles&articleId=" + articleId;
	result = httpRequest( url, "POST", urlParams );
	document.getElementById( "more-articles" ).style.display = 'none';
	document.getElementById( 'articlesFromLink' ).style.display = 'none';
	document.getElementById( 'subscription-history' ).style.display = 'block';
	document.getElementById( "subscription-history" ).innerHTML = result; 
}
function showArticlebyCateg( articleCateg ) {
	var url = "/ajax/message_retriever.php";
	var urlParams = "action=showArticlebyCateg&articleCateg=" + articleCateg;
	result = httpRequest( url, "POST", urlParams );
	document.getElementById( "more-articles" ).style.display = 'none';
	document.getElementById( 'articlesFromLink' ).style.display = 'block';
	document.getElementById( "articlesFromLink" ).innerHTML = result; 
}
function showMoreArticles() {
	var url = "/ajax/message_retriever.php";
	var urlParams = "action=showMoreArticles";
	result = httpRequest( url, "POST", urlParams );
	document.getElementById( "dashboardContainer" ).style.display = 'none';
	document.getElementById( 'more-articles' ).style.display = 'block';
	document.getElementById( "more-articles" ).innerHTML = result; 
}

function closeDiv ( id ) {
    document.getElementById(id).style.display = 'none';
}

function setErrorBoxPosition () {
        var myWidth = 0, myHeight = 0;  myWidthRight = 0;
        if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
        }
        leftSpace = Math.round ( ( (myWidth - 1100) / 2) + 330 );
        document.getElementById('error-box').style.left=leftSpace + 'px';
        document.getElementById('error-box').style.top='130px';
        
}

function setMyScansPosition () {
        var myWidth = 0, myHeight = 0;  myWidthRight = 0;
        if( typeof( window.innerWidth ) == 'number' ) {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
            //IE 6+ in 'standards compliant mode'        
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
            //IE 4 compatible        
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;        
        }
        leftSpace = Math.round ( ( (myWidth - 1100) / 2) + 420 );
        var myScansLink = document.getElementById('myScansLink')
        
        if ( myScansLink != null )  {        
            document.getElementById('myScansLink').style.left=leftSpace + 'px';
            document.getElementById('myScansLink').style.top='438px';
        }
        
        var myScansContainer = document.getElementById('seeMyScans')
        if ( myScansContainer != null ) {        
            document.getElementById('seeMyScans').style.left= ( leftSpace - 30 ) + 'px';
            document.getElementById('seeMyScans').style.top='240px';
        }
        
}

function ucwords (str) {    
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}


function autoTab(eCtrl,len)
{
  if(eCtrl.value.length >= len)  { 
    eCtrl.value = eCtrl.value.slice(0, len);
    eCtrl.form[(getIndex(eCtrl)+1) % eCtrl.form.length].focus();
  }
  return true;
}

function getIndex(eCtrl)
{
   var index = -1, i = 0, found = false;
   while (i < eCtrl.form.length && index == -1)
    if (eCtrl.form[i] == eCtrl) { index = i; } else { i++; }
   return index;
}

function showBillingFields( checkboxObj ) {
	var fieldsArray = new Array( new Array( "BILLING_ADDRESS", "25", "255" ), new Array( "BILLING_ADDRESS_2", "25", "255" ), new Array( "BILLING_CITY", "25", "255" ), new Array( "BILLING_STATE", "25", "255" ), new Array( "BILLING_ZIPCODE", "5", "5" ) );	
	for ( billingFieldCounter in fieldsArray ) {
		var billingField = fieldsArray[ billingFieldCounter ][ 0 ];
		var billingFieldSize = fieldsArray[ billingFieldCounter ][ 1 ];
		var billingFieldMaxlength = fieldsArray[ billingFieldCounter ][ 2 ];
		if ( document.getElementById( billingField ) ) {
			var parentObj = document.getElementById( billingField ).parentNode;
		}
		if ( !checkboxObj.checked ) {
			if ( document.getElementById( billingField ) ) {
				parentObj.removeChild( document.getElementById( billingField ) );				
			}		
			var fieldLabel = ucwords( billingField.replace(/_/g, ' ').toLowerCase() );
			var content = "";
			content += '<div class="formGroup" id="' + billingField + '_container" >';
			content += '	<div class="elementLabel" style="width:150px;"><em>*</em> <label for="BANK_NAME">' + fieldLabel + ': </label></div>';
			content += '	<div class="elementContainer formCheckboxElement"><div>';
			if ( billingField == 'BILLING_STATE' || billingField == 'BILLING_ZIPCODE' ) {
				url = "/ajax/signup_actions.php";
				result = httpRequest( url,  "POST",  "action=" + ( billingField == 'BILLING_STATE' ? "getStates" : "getZipcode" ) );
				content += result;
			}
			else {
				content += '		<input type="text" size="' + billingFieldSize + '" maxlength="' + billingFieldMaxlength + '" id="' + billingField + '" name="' + billingField + '" />';
			}
			content += '	</div></div>';
			content += '</div>';
			try {
				parentObj.innerHTML += content;
			}
			catch ( err ) {
				console.log( billingField );
			}
		}
		else {			
			if ( document.getElementById( billingField + '_container' ) ) {				
				parentObj = document.getElementById( billingField + '_container' ).parentNode;
				parentObj.removeChild( document.getElementById( billingField + '_container' ) );
				parentObj.innerHTML += "<input type='hidden' name='" + billingField + "' id='" + billingField + "' />";				
			}
			else {				
				parentObj = document.getElementById( billingField );				
				while ( parentObj.className != "formGroup" ) {
					parentObj = parentObj.parentNode;
				}				
				parentContainer = parentObj.parentNode; 
				parentContainer.removeChild( parentObj );
				parentContainer.innerHTML += "<input type='hidden' name='" + billingField + "' id='" + billingField + "' />";
			}
		}
	}
}
function fillUSPSSuggestion( uspsJsonDataContainerId, formName ) {	
	var uspsData = eval('(' + document.getElementById( uspsJsonDataContainerId ).innerHTML + ')');
	formObject = document.getElementById( formName );
	for ( i = 0; i < formObject.elements.length; i ++ ) {
		formElement =  formObject.elements[ i ];
		if ( formElement.name && formElement.readOnly != true ) {		
			if ( formElement.name.match( /.*Address/gi ) ) {
				formElement.value = uspsData[ 'Address2' ];
			}
			if ( formElement.name.match( /.*Address_2/gi ) ) {
				if ( uspsData[ 'State' ] != 'PR' ) {
					//alert(typeof (uspsData[ 'Address1' ]) != 'undefined');
					if ( typeof (uspsData[ 'Address1' ]) != 'undefined' ){
						formElement.value = uspsData[ 'Address1' ];
					} else	{
						formElement.value = '';
					}
				}
				else {
					if ( typeof (uspsData[ 'Urbanization' ]) != 'undefined' ){
						formElement.value = uspsData[ 'Urbanization' ];
					} else {
						formElement.value = '';
					}
				}
			}
			if ( formElement.name.match( /.*City.*/gi ) ) {
				formElement.value = uspsData[ 'City' ];
			}
			if ( formElement.name.match( /.*Zip.*/gi ) ) {
				formElement.value = uspsData[ 'Zip5' ];
			}
			if ( formElement.name.match( /.*Postalcode.*/gi ) ) {
				formElement.value = uspsData[ 'Zip5' ];
			}
			if ( formElement.name.match( /.*state.*/gi ) ) {
				formElement.value = uspsData[ 'State' ];
			}
		}
	}
}

function fillPostSuggestion( postJsonDataContainerId, formName ) {
	var postData = eval('(' + document.getElementById( postJsonDataContainerId ).innerHTML + ')');
	formObject = document.getElementById( formName );
	for ( i = 0; i < formObject.elements.length; i ++ ) {
		formElement =  formObject.elements[ i ];
		if ( formElement.name && formElement.readOnly != true ) {		
			if ( formElement.name.match( /.*Address.*/gi ) || formElement.name.match( /.*Address_2.*/gi ) || formElement.name.match( /.*City.*/gi ) || formElement.name.match( /.*Zip.*/gi ) || formElement.name.match( /.*Postalcode.*/gi ) || formElement.name.match( /.*state.*/gi )) {
				formElement.value = postData[ formElement.name ];			
			}
		}
	}
}

function backWorkflow() {
	url = "/ajax/signup_actions.php";
	var updateButtonExists = '';
	if ( document.getElementById( "updatePaymentInfoStep" ) ) {		
		updateButtonExists = true;
	}
	result = httpRequest( url,  "POST",  "action=backWorkflow&updateButtonExists=" + updateButtonExists );	
	var responeObj = eval('(' + result + ')');
	if ( responeObj[ 'showBackAlert' ] ) {
		alert("We're sorry, but clicking the back button at this time may erase your current browser session and require you to call customer service to complete your order.  Please click 'OK' below to remain on this page and complete your order.");
		location.href = "/Default/step/" + responeObj[ 'LAST_STEP' ];
	}    
}
function setPaymentValues( paymentMode ) {	
	url = "/ajax/signup_actions.php";
	result = httpRequest( url,  "POST",  "action=setPaymentValues&paymentMode=" + paymentMode);
	var responeObj = eval('(' + result + ')');
	document.getElementById( "initialPaymentValue" ).innerHTML = responeObj[ 'initialPaymentValue' ];
	document.getElementById( "recurringPaymentValue" ).innerHTML = responeObj[ 'recurringPaymentValue' ];
	
	if ( null != document.getElementById( "join_now_fee_desc" ) ) {
		document.getElementById( "join_now_fee_desc" ).innerHTML = responeObj[ 'join_now_fee_desc' ];
	}
	if ( null != document.getElementById( "join_now_pay_mode" ) ) {
		document.getElementById( "join_now_pay_mode" ).innerHTML = responeObj[ 'join_now_pay_mode' ];
	}
	if ( null != document.getElementById( "join_now_app_fee_desc_text" ) ) {
		document.getElementById( "join_now_app_fee_desc_text" ).innerHTML = responeObj[ 'join_now_app_fee_desc_text' ];
	}
}

function checkWebconferenceActive() {
	var url = "/ajax/message_retriever.php";
	$.get( url, 
		{action: 'checkWebconferenceActive'},
		function(data) {
		  if ( data == 'Success' ){
			  // redirect
			  document.location = 'WebConferencing/activation/success';
		  } else {
			  setTimeout('checkWebconferenceActive()', 1000);
		  }
		}
	);	
}
