var include_path;
var divHeight;
var divWidth;
var divTop;
var divLeft;
var loadingDivName = 'am_loading_div';
var httpObject = new Array();
var uploaded_file_name = new Array();
var uploaded_file_type = new Array();
var uploaded_file_size = new Array();
var uploaded_file_tmp_name = new Array();
var uploaded_file_error = new Array();
var uploadedCount = -1;
var uploadFormId = '';
var paramFrom;
var paramExtra;
var paramType;
var paramTodo;
var paramUpdate;
var paramForceRefresh;
var paramHash;
var paramCloseWhenDone;
var IE = document.all?true:false;
var moveObj = null;
var indexCount = 10000;
var moveOpacity = 5;
var closingTimer;
var mouseOffsetX = 0;
var currClosingOpacity;
var closingTimer = new Array();
var openingTimer = new Array();
var standardOpacity = 10;
var widgets = new Array();
var safariSubmit = false;
var upCounter = 0;

//set for drag and drop widget
if (!IE) document.captureEvents(Event.MOUSEMOVE); 

function setIncludePath(path){
	include_path = escape(path);
}

function getHTTPObject(){

	if (window.ActiveXObject)
		return  new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest)
		return new XMLHttpRequest();
	else
		return null;
}

function countExtraParams(params){
	var total = 0;
	var i = params.indexOf('=');

	while(i != -1){
		total++;
		i = params.indexOf('=', i+1);
	}
	return total;
}

function sendSubmitRequest(formId, from, extra, type, todo, update, forceRefresh, hash, closeWhenDone){
  
	//reset vars
	uploaded_file_name = new Array();
	uploaded_file_type = new Array();
	uploaded_file_size = new Array();
	uploaded_file_tmp_name = new Array();
	uploaded_file_error = new Array();
	uploadedCount = -1;
	uploadFormId = '';
	
	//store params
	paramFrom = from;
	paramExtra = extra;
	paramType = type;
	paramTodo = todo;
	paramUpdate = update;
	paramForceRefresh = forceRefresh;
	paramHash = hash;
  paramCloseWhenDone = closeWhenDone;

  //display loading  
  for(var i = 0; i < from.length; i++){
		displayLoading(from[i]);
	}
	
	//handing files upload	
	handleFile(formId);				
	return true;
}

function sendRequest(from, extra, type, todo, update, forceRefresh, hash, closeWhenDone){
				
	//reset vars
	uploaded_file_name = new Array();
	uploaded_file_type = new Array();
	uploaded_file_size = new Array();
	uploaded_file_tmp_name = new Array();
	uploaded_file_error = new Array();
	uploadedCount = -1;
	
	//store params
	paramFrom = from;
	paramExtra = extra;
	paramType = type;
	paramTodo = todo;
	paramUpdate = update;
	paramForceRefresh = forceRefresh;
	paramHash = hash;
  paramCloseWhenDone = closeWhenDone;

  //display loading  
  for(var i = 0; i < from.length; i++){
		displayLoading(from[i]);
	}
	
	//send request
	doSendRequest();
	
}

function doSendRequest(){		
	
	var from = paramFrom;
	var extra = paramExtra; 
	var type = paramType; 
	var todo = paramTodo; 
	var update = paramUpdate; 
	var forceRefresh = paramForceRefresh; 
	var hash = paramHash;
  var closeWhenDone;
			
	//get files info		
	for(i = 0; i < uploadedCount+1; i++){			
		extra = extra + uploaded_file_name[i].name + "=" + escape(uploaded_file_name[i].value) + "&";
		extra = extra + uploaded_file_type[i].name + "=" + escape(uploaded_file_type[i].value) + "&";
		extra = extra + uploaded_file_size[i].name + "=" + escape(uploaded_file_size[i].value) + "&";
		extra = extra + uploaded_file_tmp_name[i].name + "=" + escape(uploaded_file_tmp_name[i].value) + "&";
		extra = extra + uploaded_file_error[i].name + "=" + escape(uploaded_file_error[i].value) + "&";
	}
				
	//get http object
  var httpCount = httpObject.length;
	httpObject[httpCount] = getHTTPObject();
	
	var param = "type=" + type + "&todo=" + todo + '&' + extra + "&update=" + update + '&';      
	var count = 2 + countExtraParams(extra);
	
	//count vars
	var index = extra.indexOf('=');
	while(index != -1){
	  count++;
	  index = extra.indexOf('=', index+1);
	}
	
	for(var j = 0; j < from.length; j++){				
			
	  var thisDiv = document.getElementById(from[j]);
	  var inputs = thisDiv.getElementsByTagName('input');
	  var selects = thisDiv.getElementsByTagName('select');
		var textareas = thisDiv.getElementsByTagName('textarea');
	
	  for (i=0; i < inputs.length; i++) {
	
	    if (inputs[i].type == "text" || inputs[i].type == "hidden" || inputs[i].type == "password") {
	      param += inputs[i].name + "=" + escape(inputs[i].value) + "&";
	      count++;
	    }
	    if (inputs[i].type == "checkbox") {
	      if (inputs[i].checked) {
	        param += inputs[i].name + "=" + escape(inputs[i].value) + "&";
	      }
	      else {
	        param += inputs[i].name + "=&";
	      }
	      count++;
	    }
	    if (inputs[i].type == "radio") {
	      if (inputs[i].checked) {
	        param += inputs[i].name + "=" + escape(inputs[i].value) + "&";
	        count++;
	      }
	    }
	  }
	
	  for (i=0; i < selects.length; i++) {
	    var sel = selects[i]
	    if(sel.selectedIndex >= 0)
	      param += sel.name + "=" + escape(sel.options[sel.selectedIndex].value) + "&";
	    count++;
	  }
	
	  for(i=0; i < textareas.length; i++){
	    param += textareas[i].name + "=" + escape(textareas[i].value) + "&";
	    count++;
	  }
	
	}
	
	//set data and request
  
	httpObject[httpCount].onreadystatechange = function(){
	  if(httpObject[httpCount].readyState == 4){						      
			if(httpObject[httpCount].readyState == 4){
				
			  var respond = httpObject[httpCount].responseText; 
        
			  //check forwarding
			  poss = respond.search(/amhulio_forward_start:/);
			  pose = respond.search(/:amhulio_forward_end/);
			  if(poss != -1){			    
			    url = respond.substring((poss+22), (pose));			    
			    location.href = url;
			    return;
			  }
				
			  if(forceRefresh){
			    document.getElementById(update+'_content').innerHTML = respond;
		      //close widgets
          if(paramCloseWhenDone){
            for(var x = 0; x < paramCloseWhenDone.length; x++){
              var widgetInfo = findWidget(paramCloseWhenDone[x]);
              if(widgetInfo != false){
                closeDD(paramCloseWhenDone[x]);
              }
            }			    
          }
			  }
			  else if(respond != ''){		      		      		      
			    for (i=0; i < from.length; i++) {
			      var thisDiv = document.getElementById(from[i]);
			      forms = thisDiv.getElementsByTagName('form');
			      for(j = 0; j < forms.length; j++){
			      	forms[j].reset();
			      }
			    }		                
			    document.getElementById(update+'_content').innerHTML = respond;
		      //close widgets
          if(paramCloseWhenDone){
            for(var x = 0; x < paramCloseWhenDone.length; x++){
              var widgetInfo = findWidget(paramCloseWhenDone[x]);
              if(widgetInfo != false){
                closeDD(paramCloseWhenDone[x]);
              }
            }		
          }
			  }
	
			  if(hash)
			    window.location.hash = hash;
                
        //handle floating widget
        var widgetInfo = findWidget(update);                
        if(widgetInfo != false){       
          document.getElementById(update).style.display = "block";
          if(document.getElementById(update).style.opacity != standardOpacity || 
              document.getElementById(update).style.display == 'none'){    
            positionDiv(update, widgetInfo[1]);
            openDD(update);
          }           
        }
          
			}      
			hideLoading();
	  }
	}
  //fix safari problem
  var prefix = '';
	if(safariSubmit){
    prefix = '../../../';
  }
  requestPath = prefix + include_path+'lib/core/action.run.php';
  setSafari(false);
  httpObject[httpCount].open('POST', prefix + include_path+'lib/core/action.run.php', true);
	httpObject[httpCount].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject[httpCount].setRequestHeader("Content-length", count);
	httpObject[httpCount].setRequestHeader("Connection","close");
	httpObject[httpCount].send(param);
}


function handleFile(formId){	
	
  var theForm = formId;
  origAction = theForm.action;
  origTarget = theForm.target;	
  uploadFormId = theForm;
  
  var frameDiv = document.createElement('div');  
  frameDiv.id = "amuploadDiv"+upCounter;
  frameDiv.name = "amuploadDiv"+upCounter;
  frameDiv.style.position = "absolute";
  frameDiv.style.left = '-100px';
  frameDiv.style.top = '-100px';
  frameDiv.style.height = '1px';
  frameDiv.style.width = '1px';
  frameDiv.style.display = 'none';
  frameDiv.innerHTML = '<iframe id="amuploadframe" name="amuploadframe"></iframe>';
  document.body.appendChild(frameDiv);									

  theForm.target = 'amuploadframe';
  theForm.method = 'post';
  theForm.enctype= 'multipart/form-data';
  theForm.action = include_path+'lib/core/action.file.php?t='+upCounter;														  
}


function uploadingDone(tail){
	f = document.getElementById('amuploadDiv'+tail);  
	if(f){    
		uploadFormId.target = origTarget;
		uploadFormId.action = origAction;    
    if(getBrowserName() != 'Chrome' && getBrowserName() != 'Safari'){      
      document.body.removeChild(f);
    }
	}
  doSendRequest();
}

function setFileInfo(post_name, name, type, size, tmp_name, error){
	var iname = document.createElement('input');
	iname.type = 'hidden';
	iname.id = post_name + '_name';
	iname.name = post_name + '_name';
	iname.value = name;

	var itype = document.createElement('input');
	itype.type = 'hidden';
	itype.id = post_name + '_type';
	itype.name = post_name + '_type';
	itype.value = type;	

	var isize = document.createElement('input');
	isize.type = 'hidden';
	isize.id = post_name + '_size';
	isize.name = post_name + '_size';
	isize.value = size;	
	
	var itmp_name = document.createElement('input');
	itmp_name.type = 'hidden';
	itmp_name.id = post_name + '_tmp_name';
	itmp_name.name = post_name + '_tmp_name';
	itmp_name.value = tmp_name;	

	var ierror = document.createElement('input');
	ierror.type = 'hidden';
	ierror.id = post_name + '_error';
	ierror.name = post_name + '_error';
	ierror.value = error;	

	uploadedCount = uploadedCount + 1;
	uploaded_file_name[uploadedCount] = iname;
	uploaded_file_type[uploadedCount] = itype;
	uploaded_file_size[uploadedCount] = isize;
	uploaded_file_tmp_name[uploadedCount] = itmp_name;
	uploaded_file_error[uploadedCount] = ierror;			

}

function setSafari(isSafari){
  safariSubmit = isSafari;
}

function stopUploadTimer(){	
	clearTimeout(uploadTimer);
}

function setOutput(id, forceRefresh, hash){

  if(httpObject.readyState == 4){
    var respond = httpObject.responseText;

    //check forwarding
    poss = respond.search(/amhulio_forward_start:/);
    pose = respond.search(/:amhulio_forward_end/);
    if(poss != -1){
    	url = respond.substring((poss+22), (pose));
    	this.location.href = url;
    	return;
    }

    if(forceRefresh){
      document.getElementById(id).innerHTML = respond;
    }
    else if(respond != ''){
      document.getElementById(id).innerHTML = respond;
    }

    if(hash)
    	window.location.hash = hash;
  }
  hideLoading();
}

function doValidation(value, id){
	var httpObject = getHTTPObject();
	if(httpObject != null){
		//set data and request
	  httpObject.onreadystatechange = function(){
	  	if(httpObject.readyState == 4){
				document.getElementById('msg_'+id).innerHTML = httpObject.responseText;
			}
	  }
		httpObject.open('POST', include_path+'lib/core/action.validate.php', true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", 2);
		httpObject.setRequestHeader("Connection","close");
		httpObject.send('value='+value+'&id='+id);

	}
}

function hideLoading(){
	var divs = document.getElementsByTagName('div');
	for(var i = 0; i < divs.length; i++){
		var id = divs[i].id; 
		if( id.substr(0, loadingDivName.length ) == loadingDivName){
			loadingDiv = document.getElementById(id);
			document.body.removeChild(loadingDiv);
		}
	}
}

function displayLoading(id){

	if(document.getElementById(loadingDivName)){
		hideLoading();
	}
	else{
    if(document.getElementById(id).style.opacity == standardOpacity || 
        document.getElementById(id).style.display != 'none'){ 
      loadingDiv = document.createElement('div');
      loadingDiv.id = loadingDivName + '_' + id;
      loadingDiv.style.position = "absolute";
      loadingDiv.style.left = findPosX(id) + 'px';
      loadingDiv.style.top = findPosY(id) + 'px';
      loadingDiv.style.height = findHeight(id) + 'px';
      loadingDiv.style.width = findWidth(id) + 'px';
      loadingDiv.style.backgroundImage = 'url('+include_path+'lib/core/js/loading.gif)';
      loadingDiv.style.backgroundRepeat = 'no-repeat';
      loadingDiv.style.backgroundPosition = 'center';
      document.body.appendChild(loadingDiv);
    }
	}
}

function registerWidget(name, position){
  var index = widgets.length;
  widgets[index] = new Array(name, position);
}

function findWidget(id){
  for(var i = 0; i < widgets.length; i++){
     var info = widgets[i];
     if(info[0] == id)
       return info;     
  }
  return false;
}

function startDD(obj, e){
  
  var tempX, tempY;

	indexCount = indexCount + 1;
	moveObj = document.getElementById(obj);
	moveObj.style.zIndex = indexCount;	
  
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
  }  
  
  mouseOffsetX = moveObj.offsetWidth - (tempX - findPosX(moveObj.id)); 
  mouseOffsetY = tempY - findPosY(moveObj.id);
	document.onmousemove = doDD;
}

function endDD(){	
  moveObj.style.opacity = standardOpacity;
  moveObj.style.filter = "alpha(opacity='" + (standardOpacity * 10) + "')";
	moveObj = null;
	document.onmousemove = null;	  
}

function doDD(e) {
  var tempX;
  var tempY;

  
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0;}
  if (tempY < 0){tempY = 0;}  

	// cancel out any text selections
	document.body.focus();
	// prevent text selection in IE
	document.onselectstart = function () { return false; };
	// prevent IE from trying to drag an image
	moveObj.ondragstart = function() { return false; };  
  
  moveObj.style.position = 'absolute';
  moveObj.style.opacity = moveOpacity / 10;
  moveObj.style.filter = 'alpha(opacity=' + moveOpacity * 10 + ')';
  moveObj.style.top = tempY - mouseOffsetY + 'px';
  moveObj.style.left = tempX - moveObj.offsetWidth + mouseOffsetX + 'px';
  
  return true;
}

function openDD(id){
  if(document.getElementById(id).style.opacity != standardOpacity/10){
    document.getElementById(id).style.opacity = 0;
    document.getElementById(id).style.filter = 'alpha(opacity=0)'; 
    document.getElementById(id).style.display = '';
    currClosingOpacity = 0;        
    openingTimer[openingTimer.length] = setInterval("doOpen('"+id+"', " + openingTimer.length +")", 20);  
  }
}

function doOpen(id, timerIndex){
  if(currClosingOpacity < standardOpacity){
    currClosingOpacity = currClosingOpacity + 1;
    document.getElementById(id).style.opacity = currClosingOpacity / 10;
    document.getElementById(id).style.filter = 'alpha(opacity=' + currClosingOpacity * 10 + ')';    
  }
  else{      
    clearInterval(openingTimer[timerIndex]);
  }
} 

function closeDD(id){  
  currClosingOpacity = standardOpacity;
  closingTimer[closingTimer.length] = setInterval("doClose('"+id+"', " + closingTimer.length +  ")", 8);  
}


function doClose(id, timerIndex){
  if(currClosingOpacity > 0){
    currClosingOpacity = currClosingOpacity - 1;
    document.getElementById(id).style.opacity = currClosingOpacity / 10;
    document.getElementById(id).style.filter = 'alpha(opacity=' + currClosingOpacity * 10 + ')';    
  }
  else{  
    document.getElementById(id).style.display = 'none';
    clearInterval(closingTimer[timerIndex]);
  }
} 

function findWidth(id){
	return document.getElementById(id).offsetWidth;
}

function findHeight(id){
	return document.getElementById(id).offsetHeight;
}

function findPosX(id){
	obj = document.getElementById(id);
	curleft = 0;
	if(obj.offsetParent)
  	while(1){
    	curleft += obj.offsetLeft;
      if(!obj.offsetParent)
      	break;
       obj = obj.offsetParent;
     }
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(id){
	obj = document.getElementById(id);
	curtop = 0;
	if(obj.offsetParent)
		while(1){
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}

function positionDiv(id, position){

  var theDiv = document.getElementById(id);
  var divWidth = theDiv.offsetWidth;
  var divHeight = theDiv.offsetHeight;
  var winWidth = findWindowWidth();
  var winHeight = findWindowHeight();
  var scrollX = document.body.scrollLeft;
  var scrollY = document.body.scrollTop;  
  var divX;
  var divY;

  if(divHeight >= winHeight){
    divY = scrollY;
  }
  else{
    if(position == 1 || position == 2 || position == 3)
      divY = 5;		
    else if(position == 4 || position == 5 || position == 6)    
      divY = Math.ceil((winHeight - divHeight) / 2) + scrollY;    
    else if(position == 7 || position == 8 || position == 9)
      divY = winHeight - divHeight + scrollY;	
  }
  
  if(divWidth >= winWidth){
    divX = scrollX;
  }
  else{
    if(position == 1 || position == 4 || position == 7)
      divX = 5;
    else if(position == 2 || position || 5 || position == 8)
      divX = Math.ceil((winWidth - divWidth) / 2) + scrollX;
    else if(position == 3 || position == 6 || position == 9)
      divX = winWidth - divWidth + scrollX;
  }
    
  theDiv.style.position = 'absolute';  
  theDiv.style.top = divY + 'px';
  theDiv.style.left = divX + 'px';
}

function findWindowWidth() {
  var width = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    width = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    width = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    width = document.body.clientWidth;
  }
  return width;
}

function findWindowHeight() {
  var height = 0;
  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    height = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    height = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    height = document.body.clientHeight;
  }
  return height;
}

function numOnly(e, allowChars){
	pressed = (window.event) ? event.keyCode : e.which;
	c = false;
	if(allowChars)
		c = checkChars(pressed, allowChars);

	//allow common key such as back space, tab
	if(pressed >= 48 && pressed <= 57 || c || pressed == 8 || pressed == 0)
		return true;
	return false;
}

function checkChars(c, list){
	found = false;
	for(i = 0; i < list.length; i++){
		if(c == asciiValue(list[i]))
			found = true;
	}
	return found;
}

function asciiValue (c){
	c = c . charAt (0);

	var i;
	for (i = 0; i < 256; ++ i){
		var h = i . toString (16);
		if (h . length == 1)
			h = "0" + h;
		h = "%" + h;
		h = unescape (h);
		if (h == c)
			break;
	}
	return i;
}

function getBrowserName(){
  var nVer = navigator.appVersion;
  var nAgt = navigator.userAgent;
  var browserName  = '';
  var fullVersion  = 0; 
  var majorVersion = 0;
  
  // In Internet Explorer, the true version is after "MSIE" in userAgent
  if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
   browserName  = "Microsoft Internet Explorer";
   fullVersion  = parseFloat(nAgt.substring(verOffset+5));
   majorVersion = parseInt(''+fullVersion);
  }

  // In Opera, the true version is after "Opera" 
  else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
   browserName  = "Opera";
   fullVersion  = parseFloat(nAgt.substring(verOffset+6));
   majorVersion = parseInt(''+fullVersion);
  }

  // In Firefox, the true version is after "Firefox" 
  else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
   browserName  = "Firefox";
   fullVersion  = parseFloat(nAgt.substring(verOffset+8));
   majorVersion = parseInt(''+fullVersion);
  }
  
  //check chrome
  else if ( (verOffset=nAgt.indexOf("Chrome"))!=-1 )
  {
    browserName  = "Chrome";
    fullVersion  = parseFloat(nAgt.substring(verOffset+8));
    majorVersion = parseInt(''+fullVersion);     
    return browserName;
  }
  
  // In most other browsers, "name/version" is at the end of userAgent 
  else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) 
  {
   browserName  = nAgt.substring(nameOffset,verOffset);
   fullVersion  = parseFloat(nAgt.substring(verOffset+1));
   if (!isNaN(fullVersion)) majorVersion = parseInt(''+fullVersion);
   else {fullVersion  = 0; majorVersion = 0;}
  }

  // Finally, if no name and/or no version detected from userAgent...
  if (browserName.toLowerCase() == browserName.toUpperCase()
   || fullVersion==0 || majorVersion == 0 )
  {
   browserName  = navigator.appName;
   fullVersion  = parseFloat(nVer);
   majorVersion = parseInt(nVer);
  }

  return browserName;
}

