/*
url-loading object and a request queue built on top of it
*/

/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/*--- content loader object for cross-browser requests ---*/
/*new net.ContentLoader('handlerPageUrl',javaScriptResponseFunction, 'responseArgs', onErrorFunctionOrNull, methodPOST_or_GET, paramsForPost, contentTypeNotNeededUsually);*/
net.ContentLoader=function(url,onload,onLoadParams,onerror,method,params,contentType, encodingType){
  this.url = url;
  this.req=null;
  this.onload=onload;
  this.onLoadParams=onLoadParams;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType, encodingType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType, encodingType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      if (contentType){
        this.req.setRequestHeader('enctype', encodingType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}


net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  try{ //in mozilla reading the status throws an NS_ERROR_NOT_AVAILABLE exception occasionally
  var httpStatus=req.status;
  } catch(err) {} 
  if (ready==net.READY_STATE_COMPLETE){
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.prototype.defaultError=function(){
  try{
	  htmlAlert("error fetching data!"
	    +"\n<A HREF=\"/"+this.url.substring(1,this.url.length-1)+"\" TARGET=\"_blank\" TITLE=\""+this.url+"\">GO TO URL</A>"
	    +"<hr>" + this.req.responseText
	    +"\n\nreadyState:"+this.req.readyState
	    +"\nstatus: "+this.req.status
	    +"\nheaders: "+this.req.getAllResponseHeaders(), 'There was a problem:');
    } catch (err2){}
}

 function htmlAlert(caption, title, width, height, buttonText) {
      if(!document.getElementById) {
        return;
      }
      if(title == null) {
        title = 'Alert';
      }
      a = document.getElementById('htmlAlert');
      if(!a) {
        a = document.createElement('div');
        a.id = 'htmlAlert';
      //  document.body.appendChild(a, 0);
        document.forms[0].appendChild(a, 0);
        a.style.border = 'solid 1px #ccc';
        a.style.position = 'absolute';
        a.style.background = '#eeeeee';
        a.style.zIndex   = 1000;
        a.style.display = 'none';
        a.style.top    = 50;
        a.style.left   = '50%';
        a.style.marginLeft = "-400px";
        if(width == null)
        width = 420;
        a.style.width  = width + 'px';
        if(height == null)
        height = 420;
        a.style.height = height;
        a.style.fontFamily = 'Arial, verdana, sans-serif';
        a.style.fontSize   = '12px';
        a.titlebar = document.createElement('div');
        a.titlebar.style.padding = '2px 10px';
        a.appendChild(a.titlebar);
        a.titlebar.style.background = '#999999';
        a.titlebar.style.color      = '#ffffff';
        a.content = document.createElement('div');
        a.content.style.overflow = 'auto';
        a.content.style.width =(width - 20) + 'px';
        a.content.style.height = (height - 70) + 'px';
        a.content.style.padding = '10px';
        a.appendChild(a.content);
        a.content.innerHTML = 'default alert text';
        a.buttons = document.createElement('div');
		a.appendChild(a.buttons);
		a.buttons.style.textAlign = 'center';
		a.buttons.style.padding   = '5px';
		if(!buttonText){
			a.buttons.innerHTML = '<input type="button" onclick="document.getElementById(\'htmlAlert\').style.display=\'none\'" value="OK" />';
		}else{
			a.buttons.innerHTML = '<input type="button" onclick="document.getElementById(\'htmlAlert\').style.display=\'none\'" value="'+buttonText+'" />';
		}
      }
      a.style.display = 'block';
      a.content.innerHTML = caption;
      a.titlebar.innerHTML = title;
      window.scrollTo(0,0);
}

function response(){
	eval(this.req.responseText);
//	var scr = document.createElement('script');
//	scr.setAttribute("language",  "javascript");
//	scr.setAttribute("type",  "text/javascript");
//	scr.text = this.req.responseText;
//	document.getElementsByTagName('form')[0].appendChild(scr);
}

function pickPhotoFilePath(rootId){
	var email = document.getElementById(rootId + '.HomeEmailAddress').value;
	if(email.length < 5){
		alert('Please specify the home email address to use for photo');
		return;
	}
	htmlAlert('<iframe id="photoPicker_uploadTarget" name="photoPicker_uploadTarget" src="PhotoPicker.aspx?email='+email+'&rootId='+rootId+'" style="width:100%; height:100%;border:0;"></iframe>', "Photo Chooser", 400, 400, 'Cancel');
}

function hideHtmlAlert(){
	parent.document.getElementById('htmlAlert').style.display='none';
}

function selectPhoto(path, rootId){
	parent.document.getElementById(rootId + '.PhotoFilePath').value=path;
	parent.document.getElementById('htmlAlert').style.display='none';
}

function photoResponse(){
	document.getElementById('htmlAlert').innerHTML = this.req.responseText;
}

function getQueryArray()
{	
	var qsParm = new Array(); 
	var query = window.location.search.substring(1); 
	var parms = query.split('&'); 
	for (var i=0; i<parms.length; i++) { 
	var pos = parms[i].indexOf('='); 
	if (pos > 0) { 
		var key = parms[i].substring(0,pos); 
		var val = parms[i].substring(pos+1); 
		qsParm[key] = val; 
		} 
	} 
	return qsParm;
}

// .Net only allows one form so this is acceptable, otherwise we would want the form id
// !! this will only submit form elements whose id start with rootId !! an easy way to get around the 1form limit for .net
function getForm(formType, divId, rootId, tableName, pk){
	var elements = document.forms[0].elements;
	var formString = '';
	if(formType){
		formString += 'type=' + formType;
		formString += '&table=' + tableName;
		formString += '&divId=' + divId;
		formString += '&rootId=' + rootId;
		formString += '&entityId=' + pk;
		for(var i=0; i<elements.length; i++) {
			if(elements[i].name != '__VIEWSTATE' && (elements[i].id.substr(0, rootId.length) == rootId) )
			formString += '&' + elements[i].id + '=' + elements[i].value;
		}
	}else{
		var started = false;
		for(var i=0; i<elements.length; i++) {
		if(started){
		formString += '&' + elements[i].id + '=' + elements[i].value;
		}else{
			formString += '?' + elements[i].id + '=' + elements[i].value;
			started = true;
		}
	}
	}
	return formString;
}

function getFormWithAddedElement(elementNameToAdd){
	var elements = document.forms[0].elements;
	var formString = '';
	var started = false;
	for(var i=0; i<elements.length; i++) {
		if(started && elements[i].id != '__VIEWSTATE'){
		formString += '&' + elements[i].id + '=' + elements[i].value;
		}else if(elements[i].id != '__VIEWSTATE'){
		formString += '?' + elements[i].id + '=' + elements[i].value;
		started = true;
		}
	}
	formString += '&' + elementNameToAdd + '=' + 'true';
	return formString;
}