/***********************************************
* Dynamic Ajax Content- � Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""
var page_request = false

function ajaxpage(url, containerid, commands, do_not_jump){
	/* fetches url, inserts response into container element,
	then runs commands. */
	new Ajax.Updater(containerid,url, {
	  evalScripts: true,
	  onComplete : function(transport){
	  	after_comp(containerid, commands, do_not_jump);
	  }
	});
}

function ajaxPOST(url, postString, containerId, command, do_not_jump){
	/* posts url, inserts response into container element,
	then runs command */
	
	new Ajax.Updater(containerId, url, {
		method:'post',
		parameters:postString,	  
		evalScripts: true,
		onComplete: function(transport){
		  	aftercomp(containerId, command, do_not_jump)
	  	}
	});
}

function after_comp(containerid, commands, do_not_jump){
	checkforwysiwyg();
	run_or_eval(commands);
	if(do_not_jump!=true){
		Effect.ScrollTo(containerid, {offset:-60, duration:0.25});
	}
}
/*
function ajaxpageByObj(url, obj){
	var page_request = false
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else{
		return false
	}
	page_request.onreadystatechange=function(){
		loadpageByObj(page_request, obj)
	}
	if (bustcachevar) //if bust caching of external page
	bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
}
*//*
function loadpage(page_request, containerid, commands, do_not_jump){	
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
		document.getElementById(containerid).innerHTML=page_request.responseText;
		if(do_not_jump!=true){
			if (Effect) { // use scriptaculous 
				Effect.ScrollTo(containerid, {offset:-60, duration:0.25});
			} else {
				window.scrollTo(getElementLeft(containerid),getElementTop(containerid)-60);
			}
		}
		runjs(page_request.responseText);
		if(commands!=undefined){
			run_or_eval(commands);
		}
	}
}

function runjs(text){
	text = text.replace(/\r\n|\r|\n/g, ' ');
	var reg = new RegExp("<script[^>]*>(.*?)<\/script>");
	var scripts = reg.exec(text);
	if(scripts!=null){
		var s = "";
		for (i = 1; i < scripts.length; i++) {
			s = s + scripts[i] + "\n";
		}
		try{
			eval(s);
		}catch(e){
			alert(e.message);
		}
	}
}*/

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Added by: Peter B; 10 Nov 2008
//	add row of textboxes append content to div
//	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
var msgDiv=5;
function addRow(divid)
{
	var innerDiv = document.createElement("div");
	innerDiv.id = "cont";
	
//add the boxes
	addTextBox(innerDiv,"email[]","Email",msgDiv,true);
	addTextBox(innerDiv,"name[]","Name",msgDiv,true);
	addTextBox(innerDiv,"company[]","Company");
	
// add the message div
	var cell = document.createElement("div");
		cell.id = "new_row_cnt";
	var mDiv = document.createElement("div");
		mDiv.id = msgDiv;
		mDiv.style.color="#FF0000";
				
	cell.appendChild(mDiv);
	innerDiv.appendChild(cell);
	
	var myDiv = document.getElementById(divid);	
	myDiv.appendChild(innerDiv);
	msgDiv++;
}*/

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Added by: Peter B; 10 Nov 2008
//	add textbox on the fly append content to div
//	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
function addTextBox(divid,identifier,descriptor,msgDiv,addevent)
{
	  var type = "text";
	  
   // cell container to hold each field and its label
	  var cell = document.createElement("div");
		  cell.id = "new_row_cnt";
	  

      var myDiv = divid;//document.getElementById(divid);
      var newText = document.createElement("INPUT");
      var newLabel = document.createElement("LABEL");

   // These are here just to look better for the example
      var br1 = document.createElement("BR");

      newText.type = type;
      newText.name = identifier;
      
      newLabel.innerHTML = descriptor;
  // add event to 
      if(addevent != undefined)
      {
      	if(identifier.indexOf('email')!=-1)
      	{
      		newText.id = 'email_'+msgDiv;
      	  	var event = "checkEmail(this.value,'"+ msgDiv +"')";
      	}
      	else
      	{
      		newText.id = 'name_'+msgDiv;
      		var event = "isTextEmpty(this.value,'"+ msgDiv +"')";
      	}
      	 newText.setAttribute('onBlur',event);
      	
      }

      cell.appendChild(newLabel);
      cell.appendChild(br1);
      cell.appendChild(newText);
      
      myDiv.appendChild(cell);
	
}
*//*
function loadpageByObj(page_request, obj){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
		obj.innerHTML=page_request.responseText
}

function loadobjs(){
	if (!document.getElementById)
		return false;
	
	for (i=0; i<arguments.length; i++){
		var file=arguments[i]
		var fileref=""
		if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
			if (file.indexOf(".js")!=-1){ //If object is a js file
				fileref=document.createElement('script')
				fileref.setAttribute("type","text/javascript");
				fileref.setAttribute("src", file);
			}
			else if (file.indexOf(".css")!=-1){ //If object is a css file
				fileref=document.createElement("link")
				fileref.setAttribute("rel", "stylesheet");
				fileref.setAttribute("type", "text/css");
				fileref.setAttribute("href", file);
			}
		}
		if (fileref!=""){
			document.getElementsByTagName("head").item(0).appendChild(fileref)
			loadedobjects+=file+" " //Remember this object as being already added to page
		}
	}
	return true;
}
*/
function ajaxinfo(url, commands){
	makeGETRequest(url);
	http_request.onreadystatechange = function() {
		if(http_request.readyState == 4 && http_request.status == 200) {
			addinfo(http_request.responseText);
		}
	}
}

function addinfo(text){
	/**	Create Div **/
	removeinfo(false);
	var element = document.createElement("div");
	element.id = "ajax-infobar";
	element.setAttribute("align","center");
	element.style.margin = "0px auto";
	element.className ="dynamicDiv";
	element.innerHTML = text;
	document.body.appendChild(element);
	new Effect.Appear(element.id, {duration:.3, from: 0.0, to: 1.0, afterFinish: function() { element.style.opacity=1;window.setTimeout('removeinfo()',5000)}}); 
	//Effect.afterFinish = "";
 }

 function removeinfo(fade){
 	element = $('ajax-infobar');
 	if(element==null){
 		return;
 	}
 	if(fade==undefined){
 		fade = true;
 	}
 	if(fade==false){
 		document.body.removeChild(element);
 	}else{
 		Effect.Fade('ajax-infobar',{afterFinish: function(){document.body.removeChild(element);}});
 	}
 }
 
 function ajaxpopup(url, commands){
 	closeajaxpopup();
 	var element = document.createElement("div");
	element.id = "ajax-smallframe";
	document.body.appendChild(element);
	ajaxpage(url, 'ajax-smallframe', commands, true);
	positionDiv('ajax-smallframe'); 
	window.onresize="posDiv";
	window.onkeypress=checkesc;	
}
 
function closeajaxpopup() {
	element = $('ajax-smallframe');
 	if(element==null){
 		return;
 	}
 	try{
		var objs = document.getElementById('ajax-smallframe');
		objs.style.display = 'none';
		var obj2 = document.getElementById('fade-out');
		obj2.style.display = 'none';
		var obj3 = document.getElementById('as_friend');
		if(obj3 != null && obj3.style) {
			obj3.style.display = 'none';
		}
 	}catch(e){}
	window.onresize = '';
	window.onkeypress='';
	//remove div from DOM
	document.body.removeChild(element);
}

 function slideDiv(id){
 	element = $(id);
 	new Effect.toggle(element.id, 'slide', {duration:1, toggle:true});
 }
 
 function toggleImage(img){ // to invert the arrow on collapsing slideDiv
 	img1 = "images/ico-arrow.gif";
 	img2 = "images/ico-arrow-down.gif";
	if (document[img].src.indexOf(img1)!= -1){	
	 document[img].src = img2;
	}
	else{
		document[img].src = img1;
	}
 }

function checkesc(e){
	
	if(window.event) // IE
  	{
  		e=window.event;
  	}
  	if(e.charCode){
  		var keynum = e.charCode;
  	}else{
  		var keynum = e.keyCode;
  	}
  	if(keynum==27){
  		closeajaxpopup();
  	}
}

function posDiv() {
	positionDiv('ajax-smallframe');
}

function repositionDiv(){
	if(objs.style.display == 'none' || objs.style.display == '' || objs.style.display == 'undefined'){
		return;
	}
	var objs = document.getElementById(id);
	var obj2 = document.getElementById('fade-out');
	var width = getViewportSize("width");
	var height = getViewportSize("height");
	posleft = (width/2) - 250;
	postop = (height/2) - 250;
	if(posleft < 0) posleft = 0;
	if(postop < 0) postop = 0;
	objs.style.left = posleft + 'px';
	objs.style.top = postop + 'px';
	objs.style.display = 'block';
	//obj2.style.display = 'block';
	return true;
}

function positionDiv(id) {
	var objs = document.getElementById(id);
	var obj2 = document.getElementById('fade-out');
	var width = getViewportSize("width");
	var height = getViewportSize("height");
	posleft = (width/2) - 250;
	postop = (height/2) - 250;
	if(posleft < 0) posleft = 0;
	if(postop < 0) postop = 0;
	objs.style.left = posleft + 'px';
	objs.style.top = postop + 'px';
	objs.style.display = 'block';
	//obj2.style.display = 'block';
	return true;
}

function getViewportSize(dimwanted) {
	var viewportwidth;
	var viewportheight;
 
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	 }
 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

	else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
	{
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	}
 	// older versions of IE
 
 	else
	{
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}

	if(dimwanted == "width") {
		return viewportwidth;
	}else{
		return viewportheight;
	}
}

/***********************************************
* Dynamic Ajax Post/Get Requests
* 
*
***********************************************/

//var http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari, IE7...
  	try{
  		var http_request = new XMLHttpRequest();
  	}catch (err){}
     //http_request.overrideMimeType('text/html');
  } else if (window.ActiveXObject) { // IE <7
     try { 
     	var http_request = new ActiveXObject("Msxml2.XMLHTTP"); 
     } 
     catch (e) { 
     	try 
     	{ 
     		var http_request = new ActiveXObject("Microsoft.XMLHTTP"); 
     	} 
     	catch (e) 
     	{} 
     }
  }
  
function makePOSTRequest(url, parameters) {
	
	
  if (!http_request) { alert('Cannot create XMLHTTP instance'); return false; }
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function makeGETRequest(url) {
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
     http_request = new XMLHttpRequest();
     //http_request.overrideMimeType('text/html');
  } else if (window.ActiveXObject) { // IE
     try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} }
  }
  if (!http_request) { alert('Cannot create XMLHTTP instance'); return false; }
  http_request.open('GET', url, true);
  http_request.send(null);
}

function ajaxSubmit(obj, page){
	//ajax submit to be used from other js functions
	var str = getChildInputValues(obj);
	makePOSTRequest(page, str);
	return http_request
}

function doAjaxSubmit(formid, submitPage, containerid, do_not_jump, commands){
	
	//will submit form and echo response to page
	//ajaxSubmit($(formid),submitPage);
	var str = getChildInputValues($(formid));
	return ajaxPOST(submitPage, str, containerid, commands, do_not_jump);
	/*
	
	
	http_request.onreadystatechange = function() {//Call a function when the state changes.
		if(http_request.readyState == 4 && http_request.status == 200) {
			//document.getElementById(tdiv).innerHTML = "done";
			document.getElementById(containerid).innerHTML = http_request.responseText;
			document.location.hash="#submit"
			//runjs(http_request.responseText);
			if(do_not_jump!=false){
				if (Effect) { // use scriptaculous 
					Effect.ScrollTo(containerid, {offset:-60, duration:0.25});
				} else {
					window.scrollTo(getElementLeft(containerid),getElementTop(containerid)-60);
				}
			}
			try{widgInit();}
			catch(e){}
			if(commands!=undefined){
				run_or_eval(commands);
			}
		}
	}*/
}

function ajaxPostCommand(url, postString, command){
	//will submit form and call command(responseText)
	makePOSTRequest(url, postString);
	http_request.onreadystatechange = function() {//Call a function when the state changes.
		if(http_request.readyState == 4 && http_request.status == 200) {
			try{ command(http_request.responseText); }
			catch(err){
			}
		}
	}
}

/* Make a post request, and cause the response text to 
popup in a notification bar at the top of the page. */
function ainfoPOST(url, postString){
	ajaxPostCommand(url, postString,
		function(responseText){
			addinfo(responseText);
		}
	);
}

function getChildInputValues(obj){
	var str = "";
	var inputs = obj.getElementsByTagName("INPUT");
	var selects = obj.getElementsByTagName("SELECT");
	var textareas = obj.getElementsByTagName("TEXTAREA");
if(inputs.length>0){
		for (var i = 0; i < inputs.length; i++){
			if (inputs[i].type == "text" || inputs[i].type == "password" || inputs[i].type == "hidden" || inputs[i].type=="file") {
				str += inputs[i].name + "=" + escape(inputs[i].value) + "&";
			}
			if (inputs[i].type == "checkbox") {
				if (inputs[i].checked) {
					str += inputs[i].name + "=" + escape(inputs[i].value) + "&";
				} else {
					str += inputs[i].name + "=&";
				}
			}
			if (inputs[i].type == "radio") {
				if (inputs[i].checked) {
					str += inputs[i].name + "=" + escape(inputs[i].value) + "&";
				}
			}
		}
	}
	
	if(selects.length>0){
		//check if mutiples can be selected
		for (var i = 0; i < selects.length; i++){
			var tempstring = "";
			if(selects[i].multiple){
				//if ($(selects[i]).hasClassName('right_select')) {
				if(document.getElementById('pseudo_'+selects[i].id)){
					// element is part of a multi-select compound widget, 
					// use every item for submission:
					for (var j=0; j<selects[i].options.length; j++){
						//alert( selects[i].options[j].value);
						str += selects[i].name + "=" + escape(selects[i].options[j].value) + "&";
    				}
				}else{
					while (selects[i].selectedIndex != -1) { 
						str += selects[i].name + "=" + escape(selects[i].value) + "&";
						selects[i].options[selects[i].selectedIndex].selected = false;
					}
				}
				
			}else{
				str += selects[i].name + "=" + selects[i].value + "&";
			}
		}
	}
	if(textareas.length>0){
		for (var i = 0; i < textareas.length; i++){
			str += textareas[i].name + "=" + escape(textareas[i].value) + "&";
		}
	}
	return str;
}



/********************************************
**
**Enter User Defined Ajax Functions Below
*********************************************/


function doZip(zip, commands){
	ajaxpage('/ajax_main_getCityState&zip='+zip, 'city_state', commands, true);
}

function docity(state_id, city_id, div){
	//get all selected states	
	obj = $(state_id);
	stastr = ''
	for (var i=0; i<obj.options.length; i++){
   		stastr += obj.options[i].value + ';';
	}
	obj = $(city_id)
	citstr = ''
	if(obj){
		for (var i=0; i<obj.options.length; i++){
   			citstr += obj.options[i].value + ';';
		}
	}
	//str holds listing of states - send through ajax.
	new Ajax.Updater(div,'/ajax_main_make_city_listing&fid='+city_id, {
			method:'post',
			postBody:'states='+stastr+'&cities='+citstr
		}
	)
}

function editjob(id){
	alert('deprecated - ajax.js editjob' );
}

function deletejob(id){
	alert('deprecated - ajax.js deletejob' );
}

function archivejob(id){
	alert('deprecated - ajax.js archivejob' );
}

function doApply(){
	alert('deprecated - ajax.js doApply' );
}

function requestNewInterviewTime(id, homepage){
	alert('deprecated - ajax.js  requestNewInterviewTime' );
}

/****************************************************
Generic library, refactor out of ajax.js in next rev.
*****************************************************/

/** Runs command parameter if it is a function or string. */
function run_or_eval(command, quiet_error){
	if (typeof command == typeof alert){
		return command();
	} else if (quiet_error==true){
		try{
			return eval(command);
		}catch (e){
			return 'eval failed';
		}
	} else {
		return eval(command);
	}
}

/** Returns a PeriodicExecuter that checks if the observable
value has changed, and runs onChanged if appropriate. 
e.g 
	changeObserver("$F('form_field_x')", 2, "alert('X changed.')");
*/
function changeObserver(observable, frequency, onChanged){
	
	var container = { func: observable,
		lastvalue : run_or_eval(observable),
		callback : onChanged };
		
	function periodic(x){
		var newvalue = run_or_eval(container.func);
		if (container.lastvalue != newvalue){
			container.lastvalue = newvalue;
			run_or_eval(container.callback);
		}
	}
	
	return new PeriodicalExecuter(periodic, frequency);
}
