// trim functions
function lTrim(s) { return s.replace(/^\s+/g,''); }
function rTrim(s) { return s.replace(/\s+$/g,''); }
function trim(s) { return rTrim(lTrim(s)); }

//text field validation

function ThisFormValidate(form,field_ids, field_names)
{

    var fids = field_ids.split(",");
    var fnames = field_names.split(",");
    for(i=0; i < fids.length; i++) {
        var e = form.getElementById(fids[i]);
        if (!e) continue;
        if (trim(e.value) != "") continue;
        alert ("Please enter a value in the " + fnames[i] + " field.");
        return (false);
    }
    return (true);
}


function FormValidate(lst, lstnames)
{

    var lstarray1 = lst.split(",");
    var lstarray2 = lstnames.split(",");
    for(i = 0; i < lstarray1.length; i++ )
    {

        if(trim(document.getElementById(lstarray1[i]).value) == "" )
        {
            alert ("Please enter a value in " + lstarray2[i] + " field.");
            return (false);
        }
    }
    return (true);
}

// check match password
function PassValidate(pwd1, pwd2)
{
        var pass1 = trim(document.getElementById(pwd1).value);
        var pass2 = trim(document.getElementById(pwd2).value);
	if (pass1 != pass2)
        {
                alert ("Confirm Password field doesn't match.");
                return (false);
        }
        else
        {
                return(true);
        }
}

//dropdown validation

function DropValidate(dd,ddisplay)
{
        var lstarray1 = dd.split(",");
        var lstarray2 = ddisplay.split(",");
        var flag=0;

         for(i=0;i<=lstarray1.length-1; i++ )
        {
                if(document.getElementById(lstarray1[i]).selectedIndex == '' )
                {
                        alert ("Please select " + " " + lstarray2[i]);
                        flag=1;
                        return (false);
                }
        }
                if(!flag) return(true);

}

// check the character count for SMS messsages

function char_count(msg_sms)
{
     msgobj=document.getElementById(msg_sms);
     var count=msgobj.value.length;
     if (count > 160)
     {
          alert ('Message can not be longer than 160 characters for sending SMS.');
          return (false);
     }
     else
     {
        return (true);
     }
}

function RadioValidate(rb, msg)
{
        var lstarray = rb.split(",");

        for (j=0;j<lstarray.length;j++)
        {

                var obj1 = document.getElementsByName(lstarray[j]);

                for (var i = 0; i < obj1.length; i++)
                {
                        if (obj1[i].checked)
                        {
                                break;
                        }
                }

                if ( i >= obj1.length)
                {
                        alert (msg);
                        return (false);
                }


        }
        return(true);
}

//used to edit adjuster information

function ShowForm(hideid, showid)
{
	/*
	ele_obj1=document.getElementById(hideid);
	ele_obj2=document.getElementById(showid);

	if(ele_obj1.style.display == '')
		ele_obj1.style.display = 'none';
	else
		ele_obj1.style.display = '';
	*/

        var hidearr = hideid.split(",");
        var showarr = showid.split(",");

	if(document.getElementById(hidearr[0]).style.display=='')
	{
          for(i=0;i<=hidearr.length-1; i++ )
          {
		document.getElementById(hidearr[i]).style.display = 'none';
		document.getElementById(showarr[i]).style.display = '';
          }
          return (true);
	}
        if(document.getElementById(hidearr[0]).style.display=='none')
        {
          for(i=0;i<=hidearr.length-1; i++ )
          {
                document.getElementById(hidearr[i]).style.display = '';
                document.getElementById(showarr[i]).style.display = 'none';
          }
          return (true);
        }
}

// used for payroll processing

function CheckTotal(lst, tot)
{
        var lstarray1 = lst.split(",");
	var total = 0;
        for(i=0;i<=lstarray1.length-1; i++ )
        {
		var chk = document.getElementById(lstarray1[i]).value;
		total = parseInt(total) + parseInt(chk);
	}
	if(total!=parseInt(tot))
	{
		alert("Check total does not match with the total amount.");
		return false;
	}
		
        else return (true);
}


// used to validate if Purchase agrrement is accepted 
function AgreeValidate(rb, msg)
{
 	var obj1 = document.getElementsByName(rb);
	for (var i = 0; i < obj1.length; i++)
	{
		if (obj1[i].checked)
                {
			if(obj1[i].value==0)
                	{
				alert (msg);
                		return (false);
			}
			break;
                }
        }
        if ( i >= obj1.length)
        {
                alert (msg);
                return (false);
        }
        return(true);
}

//formating the number as float
function formatNumber(expr, decimals)
{
        var str = "" + Math.round( eval(expr) * Math.pow(10,decimals))
        while (str.length <= decimals)
        {
                str = "0" + str
        } // maybe add some leading zeros

        var decpoint = str.length - decimals // find location of decimal point
        var result = str.substring(0,decpoint);
        if (decimals) result += "." + str.substring(decpoint,str.length);
        return result;
}

// remove radio button selection
function RemoveSelection(radname)
{
	var robj = document.getElementsByName(radname);
	for (var i = 0; i < robj.length; i++)
	{
		if (robj[i].checked)
		{
			robj[i].checked = false;
		}
	}
	if(radname == 'coffee')
	{
		document.getElementById('bunn').value = '';
		document.getElementById('buntype').selectedIndex = 0;
	}
	return;
}

//function used on openquote.php ("add this item to database" functionality)

function AddPrice(chkid,divnm,divnmtxt)
{
	var chk = document.getElementById(chkid);
	var divobj = document.getElementById(divnm);

	if(chk.checked)
	{
		divobj.style.display = '';
	}
	else
	{
		document.getElementById(divnmtxt).value='';
		divobj.style.display = 'none';
	}
}

function calValue(price,units,total)
{
	document.getElementById(total).value = formatNumber(parseFloat(price * parseInt(document.getElementById(units).value)),2);
	CalTotal();	
}

/* -- Mark message as read  -- */

function MarkMessage(msg_id,stat)
{
	//temp
	//return;	
	var upd;
	xmlhttp.open('GET', 'markmessage.php?msg='+msg_id+'&stat='+stat); 
       		
	xmlhttp.onreadystatechange = function() 
  	{ 
		upd = document.getElementById('markas_'+msg_id);
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
		{
			if(xmlhttp.responseText=='1')
			{
				upd.innerHTML = "<a href=\"javascript:MarkMessage('"+msg_id+"','0');\" class='asread'>Mark as Read</a>";
			}
			if(xmlhttp.responseText=='0')
			{
				upd.innerHTML = "<a href=\"javascript:MarkMessage('"+msg_id+"','1');\" class='asunread'>Mark as Unread</a>";
			}
			
			//document.location.reload();
        	}        
	}
	xmlhttp.send(null);
}


function ShowHideSingle(id)
{
        var lstarray1 = id.split(",");
        for(i=0;i<lstarray1.length; i++ )
        {
                if(document.getElementById(lstarray1[i]).style.display=='none')
                {
                        document.getElementById(lstarray1[i]).style.display='';
                        return;
                }
                else (document.getElementById(lstarray1[i]).style.display=='')
                {
                        document.getElementById(lstarray1[i]).style.display='none';
                        return;
                }
        }
}

//time tracker set time now
function setNow(formField) {
         today = new Date();
         sec = today.getSeconds();
         min = today.getMinutes();
         smin = min;
         if (min<10) smin = "0"+min;
         hour = today.getHours();
         shour = hour;
         if (hour<10) shour = "0"+hour;
         obj = eval("document.mytimeForm." + formField);
         obj.value = shour + ":" + smin;
}

// add an item to todo list
function AddToDo(id, userid)
{
	var item = document.getElementById(id).value;
	if(trim(item)=='')
	{
		alert("Please enter ToDo item to add.");
		return;
	}
	item = escape(item);
	varlst = "item="+item+"&user_id="+userid+"&action=add";
	ToDoAJAXContent(varlst);
	document.getElementById(id).value = '';
}
function RemoveToDo(id, userid)
{
        varlst = "itemid="+id+"&user_id="+userid+"&action=remove";
        ToDoAJAXContent(varlst);
}

function ToDoAJAXContent(varlst)
{
        var content_div = document.getElementById('listitems');
        //content_div.innerHTML = "<div class='loading'>Please wait...Loading ...</div>";
        xmlhttp.open('GET', 'managetodo.php?'+varlst,true);
	xmlhttp.onreadystatechange = function()
        {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                {
                        content_div.innerHTML = xmlhttp.responseText;
                }
        }
        xmlhttp.send(null);
}

// validate time field

function TimeFormat(timeid)
{
     var id = document.getElementById(timeid);
     var id1 = id.value;
     var len = id1.length;
     	if (id1.indexOf(":")==-1 || id1.indexOf(":")==0 || id1.indexOf(":")==len-1)
     	{
        	alert ("Please enter time in HH:MM format.");
        	id.value = '';
        	return (false);
      	}
	else
	{
		return (true);
	}
}

function CheckDuration(fldid)
{
     var id = document.getElementById(fldid);
     var id1 = id.value;
     if(id1!='')
     {
	return ( TimeFormat('duration') && FormValidate('notes','Notes'));
     }
     else return ( FormValidate('start,finish,notes','Start Time,Finish Time,notes') && TimeFormat('start') && TimeFormat('finish'));
}

function CheckAssignment(lst)
{
  var lstarray1 = lst.split(",");
  var flag=0;
  for(i=0;i<=lstarray1.length-1; i++ )
  {
  	if(document.getElementById('user_'+lstarray1[i]).selectedIndex != '' )
                {
  			if(document.getElementById('project_'+lstarray1[i]).selectedIndex == '' )
			{
                        	alert ("Please select Project.");
                        	flag=1;
                        	return false;
			}
                }
   }    
   if(!flag)
	return true;
}
