//
// JavaScript Common functions
// Copyright (c) 2006 e-Xan
//

// This is variable for storing callback function
var ae_cb = null;
 
// this is a simple function-shortcut
// to avoid using lengthy document.getElementById
function ae$(a) { return document.getElementById(a); }
 
// This is a main ae_prompt function
// it saves function callback 
// and sets up dialog
function ae_prompt(cb, q, a) {
	ae_cb = cb;
	ae$('aep_t').innerHTML = document.domain + ' question:';
	ae$('aep_prompt').innerHTML = q;
	ae$('aep_text').value = a;
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = '';
	ae$('aep_text').focus();
	ae$('aep_text').select();
}
 
// This function is called when user presses OK(m=0) or Cancel(m=1) button
// in the dialog. You should not call this function directly.
function ae_clk(m) {
	// hide dialog layers 
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = 'none';
	if (!m)  
		ae_cb(null);  // user pressed cancel, call callback with null
	else
		ae_cb(ae$('aep_text').value); // user pressed OK 
}

function showMessage(visible) {
  if (visible) {
    document.getElementById('messagearea').style.display = "";
  } else {
    document.getElementById('messagearea').style.display = "none";
  }
}

function show_hide_obj()
{
  var args = show_hide_obj.arguments;
  var obj = document.getElementById(args[0]);
	
  if (args.length == 2){
    obj.style.display = args[1];
  } else {
	  if(obj.style.display == "none"){
		obj.style.display = "";
	  }else{
		obj.style.display = "none";
	  }
  }
}

function toggleLayer( whichLayer )
{
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function xfindObj(n, d) {
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=xfindObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function xvalidateForm() {
  var i,p,q,nm,test,num,min,max,errors='',args=xvalidateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=xfindObj(args[i]);
    if (val) { nm=val.title; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function comparev(val1, val2) {
  var v1, v2, errors='';
  v1 = xfindObj(val1);
  v2 = xfindObj(val2);
  if (v1.value != v2.value){ 
    errors = "Passwords don't match";
	alert('The following error(s) occurred:\n'+errors);
  }
  return (errors == '');
}

function xconfdel(){
  return confirm('Are you sure that you want to remove this item?');
}

function xValidateDate(obj){
  var re = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
  var result = (obj.value == '') || (
	(re.exec(obj.value)) && 
	(RegExp.$1 > 2000) && 
	(RegExp.$2 >= 1) && (RegExp.$2 <= 12) && 
	(RegExp.$3 >= 1) && (RegExp.$3 <= 31)) ;
  if (result) {
    obj.style.border = "";
    return true
  } else {
    obj.style.border = "2px solid #FF0000";
    alert('Invalid date format. Please use "YYYY-MM-DD" format for date field.');
	obj.focus();
	obj.select();
    return false;
  }
}

function xJumpMenu(targ,selObj,restore){
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

// This function returns an XMLHttpRequest object, if possible.
// For most browsers, this is a javascript object
// For IE, it is an ActiveXObject
function getReq()
{
  // code for Mozilla, etc.
  if (window.XMLHttpRequest)
  {
    return ( new XMLHttpRequest() )
  }
  // code for IE
  else if (window.ActiveXObject)
  {
    return ( new ActiveXObject("Microsoft.XMLHTTP") )
  }
  else
  {
    return ( null );
  }
}

// This function takes an existing XMLHttpRequest, an HTML element,
// and a URL as parameters. It makes the request to the URL, and
// applies the response to the HTML element as its innerHTML.
// Note how the statechange function is hooked into the request object.
function fill(req, element, url)
{
if (req!=null)
  {
  req.onreadystatechange = function()
    {
    if (req.readyState==4)
      {
      // if "OK"
      if (req.status==200)
        {
		  //alert('Changes Saved');
          //document.getElementById(element).innerHTML=req.responseText
        }
      else
        {
		  alert('Error Updating Record');
          //document.getElementById(element).innerHTML="Problem retrieving data:" + req.statusText
        }
      }
    }
  req.open("GET",url,true)
  req.send(null)
  }
else
  {
  alert("Your browser does not support XMLHTTP.")
  }
}

function lookup(req, element, url)
{
  if (document.getElementById(element)==null)
    alert('Unknown Element: ' + element);
  if (req!=null)
  {
    req.onreadystatechange = function()
    {
      if (req.readyState==4)
      {
        // if "OK"
        if (req.status==200)
        {
		  if (req.responseText!='')
		  {
		      document.getElementById(element).value=req.responseText;
		  }
        }
      }
    }
    req.open("GET",url,true)
    req.send(null)
  }
  else
  {
    alert("Your browser does not support XMLHTTP.")
  }
}

function UpdateRecord(element)
{
	if (document.forms[element].elements["error_code"].value != '')
	{
		document.forms[element].elements["error_code"].style.color = "#FFFFFF";
		document.forms[element].elements["error_code"].style.backgroundColor = "#FF5B5B";
	}
	else
	{
		document.forms[element].elements["error_code"].style.color = "#000000";
		document.forms[element].elements["error_code"].style.backgroundColor = "#FFFFFF";
	}
//	alert(document.forms[element].elements["orderno"].value);
	var qtxt = document.URL+'&cmd=savetracking'+
		'&orderno='+escape(document.forms[element].elements["orderno"].value)+
		'&material_date='+escape(document.forms[element].elements["material_date"].value)+
		'&cut_date='+escape(document.forms[element].elements["cut_date"].value)+
		'&sew_date='+escape(document.forms[element].elements["sew_date"].value)+
		'&press_date='+escape(document.forms[element].elements["press_date"].value)+
//		'&haserrors='+escape(document.forms[element].elements["haserrors"].value)+
		'&error_code='+escape(document.forms[element].elements["error_code"].value)+
		'&error_text='+escape(document.forms[element].elements["error_text"].value)+
		'&dispatch_date='+escape(document.forms[element].elements["dispatch_date"].value)+
		'&awgbillno='+escape(document.forms[element].elements["awgbillno"].value);
	//alert(qtxt);
	fill(getReq(), '', qtxt);
}

var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
    cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(frm, id, format, showsTime, showsOtherMonths) {
//  var el = document.getElementById(id);
  var el = document.forms[frm].elements[id];
 
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
	cal.flat = true;
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
//  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar
  _dynarch_popupCalendar.showAtElement(el, "Br");        // show the calendar

  return false;
}

function ShowPDF(pRGUID,pUSR,pPWD)
{
  window.open('/PDF?RGUID='+pRGUID+'&usr='+pUSR+'&pwd='+pPWD);
}

function popUp(URL, pTitle) 
{
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=1024,height=768');");
}

function popUp2(pURL, pTitle)
{
  var lTitle = '<center> :: ' + pTitle + ' :: </center>'; 
	
  Shadowbox.init();
	  
  Shadowbox.open({
        player:     'iframe',
        title:      lTitle,
        content:    pURL,
        height:     600,
        width:      800
    });
}

function DoSendMail(){
	if (document.login.user.value=='')
		alert('Please fill in your email address');
	else 
    location.href="/WebReg/index.htm?cmd=reminder&email=" + document.login.user.value;
}

