 

// Copyright (c) NimbleCat, 2008

/*
* this object wraps a DOM element
* 
* */
// make sure that the required includes are there
 if (typeof NC.util == 'undefined') {
       alert("ajaxv2.js requires the NC JavaScript framework");
 }

 
 (function () {

 NC.util.AjaxManager = function() {
	/* private variables and methods */
	var MainFrameHistory = new Array; // maintains a history of url's placed in the main frame
	var CurrentHistoryPointer = -1; // no history at start

	var gHistoryTargetIFrameName = 'historyFrame';
	var gHistoryTargetFormName= 'historyForm';
	var gHistoryIndexFieldName = 'historyIndex';
	var gHistoryFormSubmitCount = 0;
	var StrMainFrame = 'MainFrame';
	
	var StrHeaderLocation = 'Location: ';
	var StrDraft = 'Draft';
	var StrNewJob = 'NewJob';
	var StrJobId = 'JobId';
	var StrJobTitle = 'JobTitle';
	var StrJobReqNumber = 'JobReqNumber';
	var StrResponseEmail = 'ResponseEmail';
	var StrPreviousResponseEmail = 'PreviousResponseEmail';

	var StrPrimaryCategory = 'PrimaryCategory';
	var StrPrimaryCategoryScore = 'PrimaryCategoryScore';
	var StrSecondaryCategory = 'SecondaryCategory';
	var StrSecondaryCategoryScore = 'SecondaryCategoryScore';
	
	var StrManagerScoreCode = 'ManagerScoreCode';

	var StrLocation = 'Location';
	var StrZipCode = 'ZipCode';
	var StrCityState = 'CityState';

	var StrMinExperience = 'MinExperience';
	var StrMaxExperience = 'MaxExperience';
	var StrSpecificCompanies = 'SpecificCompanies';

	var StrRequiredDegree = 'RequiredDegree';
	var StrSchoolRank = 'SchoolRank';
	var StrSpecificSchools = 'SpecificSchools';

	var StrDistance = 'Distance';
	var StrRestrictToState = 'RestrictToState';

	var StrAcceptScore = 'AcceptScore';
	var StrUseMatch = 'UseMatch';

	var StrBroadcast = 'Broadcast';
	var StrEmailSelected = 'EmailSelected';

	var StrActive = 'Active';

	var StrSearchKeyWords = 'SearchKeyWords';
	var StrSearchType = 'SearchType';
	var StrSearchIndustry = 'SearchIndustry';
	var StrSearchDaysBack = 'SearchDaysBack';
	
	var DivModifiedFlag = false;
	var DivModifiedName = 'MainFrame';
	
	var NcFuncFlag = 'ncfunc:';

 	var InviteErrorMessage = 'This invite code is invalid or no longer available. To request an invite code, please click Don\'t have one? below.'
	
	/* compatibility function between V3 and V2 */

	return {
 		/* public methods */
 		
 		_xmlHttpGet:function(strURL, targetDivId, addToHistory) {
			var updater = new NC.util.AjaxUpdate( 'GET', strURL, targetDivId, targetDivId, null  /* tabview1.contentContainer */);
    		if (addToHistory) {
    			this.addMainFrameHistory( strURL);
    		}
			updater.doUpdate();
			var ct = NC.util.AjaxManager.findContentType( strURL);
			if (ct > -2  && window.oContentTabContainer != null) { // find the correct tab and highlight  it
  				var tab = window.oContentTabContainer.getTabForContentType(ct);
  				if (tab != null) {
					NC.widget.TabView.selectTab( 'ContentTabList', tab); // ContentTabList must exist on the home page... bad?
  				}
			}
		},

		_postDraft: function( url, divId, notLoggedIn)
		{
		//	alert("Post draft");
			baseFormName = 'JobEditForm';
			NC.util.Dom.setElementValue( baseFormName, StrDraft, 1); // set draft
			draftValue = NC.util.Dom.getElementValue( baseFormName, StrDraft);
		//	alert( draftValue);
			this._postUpdatedJob( url, divId, notLoggedIn);
		},

		_postSearch: function( url, divId, notLoggedIn)
		{
			var baseFormName = 'JobEditForm';
		    var form = document.forms[baseFormName];
			/*
			jobTitle = getElementValue( baseFormName, StrJobTitle);
			responseEmail = getElementValue( baseFormName, StrResponseEmail);
			zipcode = getElementValue( baseFormName, StrZipCode);
			*/
			var jobTitle = NC.util.Dom.getFormElement( form, StrJobTitle);
			var zipCode = NC.util.Dom.getFormElement(form, StrZipCode);
			if (jobTitle.value.length == 0) {
				jobTitle.value = '$'; // the search name is empty - it will be set during the submission process
			}
			if (zipCode.value.length == 0) {
				zipCode.value = '94539';
			}
		//	alert( jobTitle.value);
		//	alert( responseEmail.value);
		//	alert( zipCode.value);
			
			this._postJob( url, divId, notLoggedIn);
		},

		_postJob: function( url, divId, notLoggedIn)
		{
			var baseFormName = 'JobEditForm';
			NC.util.Dom.setElementValue( baseFormName, StrDraft, 0); // unset draft
			var draftValue = NC.util.Dom.getElementValue( baseFormName, StrDraft);
		//	alert( draftValue);
			this._postUpdatedJob( url, divId, true, notLoggedIn);
		},


		_postUpdatedJob: function( url, divId, showProgress, notLoggedIn)
		{
			var baseFormName = 'JobEditForm';
			var jobTitle = NC.util.Dom.getElementValue( baseFormName, StrJobTitle);
			var responseEmail = NC.util.Dom.getElementValue( baseFormName, StrResponseEmail);
			var zipcode = NC.util.Dom.getElementValue( baseFormName, StrZipCode);
			var primary = NC.util.Dom.getElementValue( baseFormName, StrPrimaryCategory);
			var searchKeyWords = NC.util.Dom.getElementValue( baseFormName, StrSearchKeyWords);
			var managerScoreCode = NC.util.Dom.getElementValue( baseFormName, StrManagerScoreCode);
			
			// check required categories
			var error = false;
			if (jobTitle.length == 0 ||
				responseEmail.length == 0 ||
				zipcode.length == 0) {
				this.showError( 'Please enter all the information requested in red.')
				error = true;
			}
			else if (primary == 0 &&
			    searchKeyWords.length == 0 &&
				managerScoreCode < 0) {
				if (notLoggedIn == false) {
					this.showError( 'Please select a primary category, management experience or select search key words.')
				}
				else {
					this.showError( 'Please select a professional experience category.')
				}
			    error = true;
			}
			else {		
				this.setDivModifiedFlag( false);
				NC.util.RefreshManager.setSearchPending(0);
				this._postRequest('JobEditForm', url, divId);
			}
			if (error) {
				showProgress = false;
			}
			if (showProgress) {
				var showAsPopup = false;
				this.clearError();
				if (divId.length == 0) {
					divId = NC.util.AjaxDialogDisplay.ProgressDialog;
					showAsPopup = true;
				}
	/*
				var updater = new NC.util.AjaxUpdate( 'GET', './searchInProgress.php', divId, divId, null );
				updater.doUpdate();
	*/
				var callback = null;
	  			var progressDialog = null;
	  			if (divId == 'NCPromo') {
					callback =
					{
		  			};
	  				progressDialog = './promoProgress.php';
	  			}
	  			else {
	  				progressDialog = './searchInProgress.php';
					callback =
					{
		  				ok:this.goToPreviousPage
		  			};
	  				
	  			}
				NC.widget.MessageManager.showDialog(progressDialog, divId, callback, showAsPopup, 300);
			}
			else {
				if (error == false) {
					this.showPreviousMainFrameContent();
				}
				else {
					; // stay there
				}
			}
		},
		
		goToPreviousPage: function( event, parms) {
			showPreviousMainFrameContent();
		},
		
		onDeleteJobSuccess: function( o) {
			this.showCurrentMainFrameContent();
		},
		
		onDeleteJobFailure: function( o) {
			alert( "Job deletion failed. Please contact NimbleCat Customer Support");
		},
		
		_deleteJob: function( deleteUrl, addToHistory /* historical parameter - ignored */) {
			var callback =
			{
  				success:this.onDeleteJobSuccess,
  				failure:this.onDeleteJobFailure,
				scope: this    				
			};
			var connection = new NC.util.AjaxConnection( 'GET', deleteUrl, null);
			connection.executeMethod( callback);
		},
		
		
		_postRequest: function( formName, targetUrl, divId)
		{
			var form = document.forms[ formName];
			if (form != null) {
				var postData = "";
	   			for (var i = 0; i < form.elements.length; i++) {
	   			  var element = form.elements[i];
	   			  if (!element.disabled) {
		   			if (postData.length > 0 && postData.charAt(postData.length -1) != '&') {
		   				postData += '&';
		   			}
	   		      	switch(element.type) {
	   		      	case 'hidden':
	   		      	case 'text':
	   		      	case 'textarea':
	   		      		var evalue = escape(element.value);
	   			      	postData += element.name + '=' + evalue;
	   			      	break;
	   		      	
	   			      case 'checkbox':
	   			      	if (element.checked) {
	   			      		postData += element.name + '=' + element.value;
	   			      	}
	   			      	break;
	   		      
	   			      case 'radio':
	   			      	if (element.checked) {
	   			      		postData += element.name + '=' + element.value;
	   			      	}
	   			      	break;
	   		      	
	   			      case 'select-one':
	   			      	postData += element.name + '=' + element.value;
	   			      	break;
	   		      	
	   			      case 'select-multiple':
	    				for (j = 0; j < element.length; j++) {
	    					if (element.options[j].selected) {
	    						if (postData.length > 0 && postData.charAt(postData.length -1) != '&') { // more than one selected value
	    							postData += "&";
	    						}
	    						postData += element.name + "[]=" + element.options[j].value;
	    					}
	    				}
	   			      	break;
	   		      	
	   			      default:
//	   			      	alert( 'unknown ' + element.type + ' ' + element.name);
	   			      }
	   		      }
	   		    }
	   		    var rval;
	   		    if (divId.length > 0) {	
	    			rval = this._xmlHttpPostUpdatePage(targetUrl, postData, divId);
	    		}
	    		else {
	    			rval = this._xmlHttpPostUpdateMain(targetUrl, postData);
	    		}
			}
			else {
				alert( "form not invoked");
			}
		},
		
		updatepage: function(str, divName){
		    div = document.getElementById(divName);
		    div.innerHTML = str;
		},

		replacePage: function( newSource)
		{
			window.location = newSource;
		},

		_xmlHttpPostUpdateMain: function(strURL, postData) {
			var callback =
			{
  				success:function( o) {
		    		var searchStr = StrHeaderLocation;
		    		var i = o.responseText.indexOf(searchStr);
			    	if ( i == 0) { // new url
			    		url =o.responseText.substring(i+ searchStr.length);
		//	  			updatepage(url, "MainFrame"); 
//						alert( "_xmlHttpPostUpdateMain returns: " + o.responseText);
			    		this._xmlHttpGet(url, StrMainFrame, true);
			    	}
			    	else { // a page has beeen sent
				    	if (o.responseText.length > 0) { // don't show zero length pages
				  			this.updatepage(o.responseText, StrMainFrame); 
				    	}
			  		}
//					showDoneState();
  				},

  				failure:function( o) {
  				},

				scope: this    				
			};
			var connection = new NC.util.AjaxConnection( 'POST', strURL, postData);
			connection.executeMethod( callback);
			
		},
		
		_xmlHttpPostUpdatePage: function(strURL, postData, targetDivId) {
			var callback =
			{
  				success:function( o) {
		    		var searchStr = StrHeaderLocation;
		    		var i = o.responseText.indexOf(searchStr);
			    	if ( i == 0) { // new url
			    		url = o.responseText.substring(i+ searchStr.length);
						this.replacePage( url); 
			    	}
			    	else { // a page has beeen sent
  						if( o.responseText.length > 0) {
				  			this.updatepage(o.responseText, targetDivId);
  						}
			    	}
		//	    	setStatus( '&nbsp;');
		//			showDoneState();
  				},

  				failure:function( o) {
//					setStatus( "Error: " + PostRequest.status);
					var message = "<li>Transaction id: " + o.tId + "</li>";
					message += "<li>HTTP status: " + o.status + "</li>";
					message += "<li>Status code message: " + o.statusText + "</li>";
					message += "<li>HTTP headers: <ul>" + o.getAllResponseHeaders + "</ul></li>";
					message += "<li>Server response: " + o.responseText + "</li>";
//					alert( "_xmlHttpPostUpdatePage failed: " + message);
  				},

				scope: this    				
			};
			var connection = new NC.util.AjaxConnection( 'POST', strURL, postData);
			connection.executeMethod( callback);
			
		},

		getDivModifiedFlag: function ()
		{
			return DivModifiedFlag;
		},
		
		setDivModifiedFlag: function ( value)
		{
			DivModifiedFlag = value;
		},
		
		getDivModifiedName: function ()
		{
			return DivModifiedName;
		},
		
		setDivModifiedName: function ( newName)
		{
			DivModifiedName = newName;
		},
		
		addUnprecedentedParameter: function ( parameterName, strURL)
		{
			// add an unprecedented parameter to the url to make it unique and defeat caching by IE
			if (strURL.indexOf("?") == -1) { // add the ?
				strURL += "?" + parameterName + "=" + new Date().getTime();
			}
			else { // there are other parameters so just append the new parameter
				strURL += "&" + parameterName + "=" + new Date().getTime();
			}
			return strURL;
		},
		
		findContentType: function( strURL) {
			var query = strURL.split('?');
			if (query.length == 2) {
				var parms = query[1].split('&');
				for (var i = 0; i < parms.length; i++) {
					var av = parms[i].split('=');
					if (av.length > 0 && av[0] == 'ct') {
						return av[1];
					}
				}
			}
			return -1;
		},
		
		showHistoryUrl: function( strURL) {
			var funcIndex = strURL.indexOf( NcFuncFlag);
			var ct = -2;
  			if ( funcIndex > -1) {
  				var ncFunc = strURL.substring( funcIndex + NcFuncFlag.length);
  				if (ncFunc.indexOf('showscore') >= 0) {
  					NC.widget.ResumeUploadManager.showResumeInfo( 'MainFrame');
  					ct = 7;
  				}
  				else if (ncFunc.indexOf('showjshome') >= 0) {
	  				NC.widget.MemberManager.showMemberHome();
	  				ct = -1;
  				}
  				else if (ncFunc.indexOf('showemphome') >= 0) {
	  				NC.widget.MemberManager.showEmployerHome();
	  				ct = -1;
  				}
  				else if (ncFunc.indexOf('showjsquickstart') >= 0) {
	  				NC.widget.MemberManager.showMemberQuickStart();
	  				ct = -1;
  				}
  				else if (ncFunc.indexOf('invitemember')  >= 0) {
			  		NC.widget.CandidateManager.showInvitePopup( 'inviteMemberForm.php', 'JsInviteForm', 'do_invite.php','', null, 2, -1);
	  				ct = -1;
  				}
  				else if (ncFunc.indexOf('showgetbadge')  >= 0) {
	  				NC.widget.MemberManager.showGetBadge();
	  				ct = 7;
  				}
 				else if (ncFunc.indexOf('uploadresume')  >= 0) {
					 showUploadPane('centercontent');
					ct = 7;
  				}
 				else if (ncFunc.indexOf('updateprivacy')  >= 0) {
					NC.widget.DashboardManager.showJsSelectPrivacyPopup( null,-1, false);
					ct = 7;
  				}
 				else if (ncFunc.indexOf('updateprofile')  >= 0) {
					NC.widget.ResumeUploadManager.editResumeInfo(null,'./getResumeInfo.php', 'centercontent');
					ct = 7;
  				}
 				else if (ncFunc.indexOf('showjobalertmap')  >= 0) {
					NC.widget.GmapManager.showJobAlertMap();
					ct = 1;
  				}
  				else {
//  					alert( "unknown function: " + ncFunc);
  				}
  			}
  			else {
				this._xmlHttpGet(strURL, StrMainFrame, false); 
 			}
 			if (ct == -2) { // not yet set - look in the url
				ct = this.findContentType( strURL);
 			}
			if (ct > -2  && window.oContentTabContainer != null) { // find the correct tab and highlight  it
  				var tab = window.oContentTabContainer.getTabForContentType(ct);
				NC.widget.TabView.selectTab( 'ContentTabList', tab); // ContentTabList must exist on the home page... bad?
			}
		},

		addMainFrameHistory: function( strURL)
		{
		//	CurrentHistoryPointer = MainFrameHistory.length;
			CurrentHistoryPointer += 1;
			MainFrameHistory[CurrentHistoryPointer] = strURL; // add to history
			MainFrameHistory.length = CurrentHistoryPointer + 1;
			var form = document.forms[gHistoryTargetFormName];
			var field = NC.util.Dom.getFormElement( form, gHistoryIndexFieldName);
			field.value = CurrentHistoryPointer;
			form.submit();
		//	alert( "submit: " + field.value);
			gHistoryFormSubmitCount += 1;
			this.showNavigationBar();
		},
		
		showCurrentMainFrameContent: function()
		{
			if (CurrentHistoryPointer >= 0) {
				strURL = this.addUnprecedentedParameter( "ms1", MainFrameHistory[CurrentHistoryPointer]);
//				this._xmlHttpGet(strURL, StrMainFrame, false);
				this.showHistoryUrl(strURL);
			}
		},
		
		showNextMainFrameContent: function()
		{
			if (CurrentHistoryPointer < MainFrameHistory.length - 1) {
				CurrentHistoryPointer += 1;
//				this._xmlHttpGet(MainFrameHistory[CurrentHistoryPointer], StrMainFrame, false);
				this.showHistoryUrl(MainFrameHistory[CurrentHistoryPointer]);
				this.showNavigationBar();
			}
		},

		popHistoryPointer: function () // pop the last history pointer off the stack
		{
			if (CurrentHistoryPointer > 0) {
				CurrentHistoryPointer -= 1;
			}
		},

		showPreviousMainFrameContent: function ()
		{
			if (CurrentHistoryPointer > 0) {
				CurrentHistoryPointer -= 1;
//				this._xmlHttpGet(MainFrameHistory[CurrentHistoryPointer], StrMainFrame, false);
				this.showHistoryUrl(MainFrameHistory[CurrentHistoryPointer]);
				this.showNavigationBar();
			}
			else {
				this.showCurrentMainFrameContent();
			}
		},

		
		historyIframeLoaded: function()
		{
		//	alert('history iframe loaded: ' + gHistoryFormSubmitCount);
			if (gHistoryFormSubmitCount > 1) {
		//		alert( "If you want to go back to the previous page, please use the Previous and Next buttons on this page.");
		//		showPreviousMainFrameContent();
				gHistoryFormSubmitCount -= 1;
			}
		},
		
		createNavigationBar: function ()
		{
			  navBar = '<ul  class="nextprev">';
			  prevWritten = false;
			  nextWritten = false;
			  if (CurrentHistoryPointer > 0) {
			  	navBar += '<li>| <a href="#" onclick="showPreviousMainFrameContent()">&lt;Previous</a></li>';
			  	prevWritten = true;
			  }
			  if (CurrentHistoryPointer < MainFrameHistory.length - 1) {
				  if (prevWritten) {
			  			navBar += '&nbsp;';
				  }
			  	navBar += '<li>';
			  	if (!prevWritten) {
			  		navBar += '| ';
			  	}
			  	navBar += '<a href="#" onclick="showNextMainFrameContent()">Next&gt;</a></li>';
			  	nextWritten = true;
			  }
			  navBar += '</ul>';
			  return navBar;
		},
		
		showNavigationBar: function() {
		    navigationDiv = document.getElementById('Navigation');
		    if (navigationDiv != null) {
		    	document.getElementById('Navigation').innerHTML = this.createNavigationBar();
		    }
			
		},
		
		hideNavigationBar: function() {
		    navigationDiv = document.getElementById('Navigation');
		    if (navigationDiv != null) {
		    	navigationDiv.style.display = 'none';
		    }
			
		},
		
		displayNavigationBar: function() {
		    navigationDiv = document.getElementById('Navigation');
		    if (navigationDiv != null) {
		    	navigationDiv.style.display = 'block';
		    }
			
		},
		
		displaySearchResults: function( url, divId, addToHistory) {
			/*
  			this._xmlHttpGet( url, divId, addToHistory);
  			*/
				var connection = new NC.util.AjaxConnection( 'GET', url, '');
				var callback =
				{
	  				success:function( o) {
	  					var xmltest = o.responseText.substring( 0, 5);
	  					if (xmltest == '<?xml') {
		  					var xdoc = o.responseXML;
		  					var content = '';
							if (xdoc != null) {	  					
								try {
									var success = xdoc.getElementsByTagName('success').item(0).firstChild.data;
									if (success == 1) {
										content = xdoc.getElementsByTagName('content').item(0).firstChild.data;
										var selectionId = xdoc.getElementsByTagName('selectionid').item(0).firstChild.data;
										NC.promo.PromoManager.setSelectionId( selectionId);
									}
								} catch (e) {
									alert( "Exception");
								}
							}
							else {
								content = o.responseText;
							}
	  					}
	  					else {
	  						content = o.responseText;
	  					}
						
						var processedText = connection.substituteTags( content);
						connection.refreshDivs();
						
						var div = document.getElementById( divId);
						div.innerHTML = processedText;
			    		if (addToHistory) {
			    			this.addMainFrameHistory( url);
			    		}
			    		
	  				},
	
	  				failure:function( o) {
	  				},
	
					scope: this    				
				};
				connection.executeMethod( callback);
  			
		},
		
		getNcFuncFlag: function() {
			return NcFuncFlag;
		},
		
	  	clearError: function() {
	  		var errorDiv = document.getElementById( "NCError");
	  		errorDiv.style.display="none";
	  		errorDiv.innerHTML = ""; //  hide it and remove the error message
	  	},
	  	
	  	showError: function( message) {
	  		var errorDiv = document.getElementById( "NCError");
	  		errorDiv.style.display="block";
	  		errorDiv.innerHTML = message; //  show the error message
	  	},
	  	
	  	doCandidateSearchCheckInvite: function() {
			var inviteCodeEl = document.getElementById('InviteCode');
			var inviteCode = NC.util.Dom.getValue( inviteCodeEl);
			var callback =
			{
  				success:function( o) {
  					if (o.responseText.substr(0,1) == '1') {
						var callbackInner =
						{
			  				success:function( o) {
			  				},
			
			  				failure:function( o) {
			  				},
			
							scope: this    				
						};
						var url = './incrementInviteCode.php?InviteCode=' + inviteCode;
						var connection = new NC.util.AjaxConnection( 'GET', url, '');
						connection.executeMethod( callbackInner);
				  		NC.util.AjaxManager._postSearch('do_updatejob_ajax.php', 'NCPromo', true);
  					}
  					else {
						NC.util.AjaxManager.showError( InviteErrorMessage);
  					}
  				},

  				failure:function( o) {
  				},

				scope: this    				
			};
			var url = './checkInviteCode.php?InviteCode=' + inviteCode;
			var connection = new NC.util.AjaxConnection( 'GET', url, '');
			connection.executeMethod( callback);
	  	}
	  	
		
 	}
  }	
();

})(); 	
 		