/////////////////////////////////////////////////////////////////////
//
//  Project: MWasp
//
//	MWasp_Funcs.js
//	03/18/02 Harry Walden - MWare, Inc.
//
//	Client side procedures.
//
//  Revision History
//  -----------------------------------------------------------------
//  2002-03-18  hmw Created initial version
//  2002-04-03  hmw Added the OpenEditRecord function
//  2002-05-18  hmw Added the Focus First Field function
//  2002-06-02  hmw Added the GridSort function
//  2002-12-02  hmw Added the Swap images functions from Dreamweaver for rollovers
//	2007-04-24	mwdo added bubblewrap and bubblepop functions
//	2008-03-13  hmw  Added toProperCase func
//	2009-03-25	MWDO Modified the callasp function to work in firefox
//	2009-03-25	MWDO Modified GetRsXML to make it work in IE and FIrefox
//	2009-04-09	hmw fixed issue with getrsxml cancelling changes and made teh message more verbose
//  2010-12-13  hmw Added code for cascading combo boxes
//  2011-01-11  MWDO Modified to make GetRsXML compatable with other browsers
/////////////////////////////////////////////////////////////////////

var xmlHttp;
var OkToShowTip;

function getElementByIdCompatible (the_id) {
  if (typeof the_id != 'string') {
    return the_id;
  }

  if (typeof document.getElementById != 'undefined') {
    return document.getElementById(the_id);
  } else if (typeof document.all != 'undefined') {
    return document.all[the_id];
  } else if (typeof document.layers != 'undefined') {
    return document.layers[the_id];
  } else {
    return null;
  }
}

function toProperCase(s)
{
  s = s.toLowerCase().replace(/^(.)|[\s'-.](.)/g, 
          function($1) { return $1.toUpperCase(); });
  s = s.replace(/'S/g,'\'s');
  s = s.replace(/ of /gi,' of ');
  s = s.replace(/ for /gi,' for ');
  s = s.replace(/ and /gi,' and ');
  s = s.replace(/ the /gi,' the ');
//  alert(s);          
  return s;
}

function GetXmlHttpObject(handler)
{ 
	// This function creates the request object depending on the browser
	//
	var objXmlHttp=null
	
	if (navigator.userAgent.indexOf("Opera")>=0)
	{
		alert("This example doesn't work in Opera") 
		return 
	}
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		//var strName="Msxml2.XMLHTTP"
		var strName="Microsoft.XMLHTTP"
		//if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
//		{
//			strName="Microsoft.XMLHTTP"
//		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName);
			if(handler!=null){objXmlHttp.onreadystatechange=handler;}
			return objXmlHttp;
		} 
		catch(e)
		{ 
			alert("Error. Scripting for ActiveX might be disabled"); 
			return 
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler; 
		return objXmlHttp;
	}
} 

function BubbleWrap(URL){
	//
	// Gets the content for the info bubble and then calls the function to show the tip
	//
	htm();
	OkToShowTip = true;
	xmlHttp=GetXmlHttpObject(BubbleBlown);
	xmlHttp.open("GET", URL , true);
	xmlHttp.send(null);
}

function BubbleBlown(){ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		if(OkToShowTip){
			Content = xmlHttp.responseText;
			Text[0] = ["",Content];
			stm(Text[0],Style[0]);
		}
	} 
} 

function BubblePop(){
	//
	// Pops the bubble
	//
	OkToShowTip = false;
	htm();
}

function MM_findObj(n, d) { //v4.01
  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=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function onlyonce() {
//
//  Keep the user from pressing submit more than once
//
numberoftimes += 1;

  if (numberoftimes > 1) { 
    var themessage = "Please be patient.  You have already submitted this form.  Pressing submit multiple times will result in your account being billed multiple times.  You will receive a response momentarily.";
    if (numberoftimes == 3) {
      themessage = "DO NOT PRESS SUBMIT MULTIPLE TIMES!!!  YOUR ACCOUNT WILL BE BILLED EACH TIME YOU PRESS SUBMIT!!!  Processing may take up to one minute.";
    }
    alert(themessage);
    return false; 
  } 
  else {
    return true;
  }
}


function ShowDialog(URL) {
//
//  This function opens the page specifed in the URl with a preset
//  window description
//

  window.open(URL,"_blank","left=100,height=600,width=800,scrollbars=yes");
  
}

function GridSort(Section, Field, Direction) {
//
//  this function sets the sort field for the section
//  and tells the form to post
//

  document.frm["SortSection"].value = Section;
  document.frm["OrderBy"].value = Field + " " + Direction;
  document.frm.submit();

  //alert(document.frm["OrderBy"].value);
  return false;
}

function FocusFirstField() {
//
//  Sets focus to the first available field on the form
//
var i;

  for (i=0; i<document.frm.length; i++){
    if (document.frm[i].type!="hidden") {
      if (typeof document.frm[i].disabled != 'undefined') {
        if (!document.frm[i].disabled) {
          document.frm[i].focus(); 
          if (document.frm[i].type=="text") {document.frm[i].select()}
          return;
        }
      }
    }
  }
}

function OpenEditRecord(Features, AllowAddNew, SectionName, RecordIdentifier, RecordIdentifierValue) {
//
//	Open up a page in a new window
//
//if (RecordIdentifierValue == "~") {alert("'" + RecordIdentifierValue+ "'")}

	  if (RecordIdentifierValue == "~") {
	    window.open("../RecordEditor.asp?SectionName=" + SectionName + "&RecordIdentifier=" + RecordIdentifier + "&AllowAddNew=" + AllowAddNew+ "&Features=" + Features, "_blank", Features);
	  }
	  else {
	    window.open("../RecordEditor.asp?SectionName=" + SectionName + "&RecordIdentifier=" + RecordIdentifier + "&RecordIdentifierValue=" + RecordIdentifierValue + "&AllowAddNew=" + AllowAddNew + "&Features=" + Features, "_blank", Features);
	  }
		
	return false;
}

function JiggleTheHandle() {
//
//  This function will refresh the data in the underlying window
//

  //alert(window.opener.location.href);
  window.opener.location.href = window.opener.location.href;
}

function OpenWindow(URL, Target, Features) {
//
//  This function opens the specified URL in a new window and returns false
//

  window.open(URL, Target,Features);
  return false;

}
function CallAsp(URL) {
//
//  This procedure allow the html page to call ans ASP page from the browser
//  If the page spews out anything it is returned to the calling script
//

	//	2009-03-25	MWDO Modified to make sure it is cross browser compatable
	//

	var xmlhttp = GetXmlHttpObject();
  xmlhttp.open("GET", URL, false);
  xmlhttp.send(null);
  return xmlhttp.responseText;
}

function GetRsXML(RecordID,Query,FieldList,Options) {
//
//  This function is used for retrieving an XML stream from the server
//  and populating the fields on the data entry form specified in the field list
//
//var URL = 'http://scasmartparts.com/smartparts/GetRsXML.asp?s=' + SessionID + '&u=' + UserID + '&q=' + Query + '&p1=' + RecordID
//var URL = '/admin/GetRsXML.asp?s=' + SessionID + '&u=' + UserID + '&q=' + Query + '&p1=' + RecordID
var URL = '/mwasp/GetRsXML.asp?q=' + Query + '&p1=' + RecordID

//	2009-03-25	MWDO Modified to use the GetXmlHttpObject to that it works in Firefox and IE
//
//var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
var xmlhttp = GetXmlHttpObject();
var xmldom = null;
var parser = null;
var frm = document.forms['frm'];
//var frm = getElementByIdCompatible('frm');

	
//	alert(RecordID)
//alert(this.name)

  //  20031220 hmw Check to see if we have options passed in for clearing first
  //
  if (Options) {
    if (RecordID=="") {
      var Fields = FieldList.split(",");
      for (i=0; i<Fields.length; i++) {
        //alert(Fields[i]);
        frm.elements[Fields[i]].value="";
        //  If the field has an OnChange Event, Fire it
        //
        if (frm.elements[Fields[i]].getAttribute("onChange")) {
          frm.elements[Fields[i]].onchange();
        }
      }
    }
  }

  //  Early exit if we are clearing a field
  //
  if (RecordID=="") {return true;}
  if (RecordID=="*") {return true;}

  xmlhttp.open("GET", URL, false);
  xmlhttp.setRequestHeader("Content-Type","text/xml");
  
	//	2009-03-25	MWDO Added null to the parameters
	xmlhttp.send(null);
  
	try //Internet Explorer
  {
		xmldom=new ActiveXObject("Microsoft.XMLDOM");
		xmldom.async="false";
		xmldom.loadXML(xmlhttp.responseText);
	}
	catch(e)
	{
		try //Firefox, Mozilla, Opera, etc.
		{
			parser=new DOMParser();
			xmldom=parser.parseFromString(xmlhttp.responseText,"text/xml");
		}
		catch(e)
		{
			alert(e.message);
			return;
		}
	}

  	
	//if (navigator.userAgent.indexOf("MSIE")==-1)
//	{
//		parser = new DOMParser();
//		xmldom = parser.parseFromString(xmlhttp.responseText,"text/xml");
//		//alert(xmldom.selectSingleNode("//status").text);
//	}
//	else
//	{
//	  xmldom.loadXML(xmlhttp.responseText);
//	}
//	document.write(xmlhttp.responseText);
//  if (UserID=="HWALDEN") {alert(xmlhttp.responseText);}
//	alert(xmlhttp.responseText);
//    alert(xmldom.selectSingleNode("//status").text=='0')
//	alert(xmldom.getElementsByTagName("status")[0].childNodes[0].nodeValue);

  //  2011-01-11  MWDO Modified to make compatable with other browsers
  //if (xmldom.selectSingleNode("//status").text=='0') {
  if(getXMLValue(xmldom, "status")=='0'){
    //alert(xmldom.selectSingleNode("//message").text);
    alert(getXMLValue(xmldom, "message"));
    return false;
  }else{  
    
    var Fields = FieldList.split(",");
    var msg = "";
    
    
    //  Loop though the field list and determine if we nee to prompt the user
    //  to overwite and existing information in the fields
    //
    for (i=0; i<Fields.length; i++) {
      //if (frm(Fields[i])) {
      if(frm.elements[Fields[i]]!=null){
        //if (frm(Fields[i]).value != "") {
        if(frm.elements[Fields[i]].value != ""){
          //if (xmldom.selectSingleNode("//" + Fields[i])) {
          if(getXMLNode(xmldom, Fields[i])){
            //if (frm(Fields[i]).value != xmldom.selectSingleNode("//" + Fields[i]).text) {
            //if (frm(Fields[i]).value != getXMLValue(xmldom,Fields[i])) {
            if(frm.elements[Fields[i]].value != getXMLValue(xmldom,Fields[i])){
              //if (msg != "") {msg += ", "}
              //msg += "Change " + Fields[i] + " from : " + frm(Fields[i]).value + " to : " + xmldom.selectSingleNode("//" + Fields[i]).text +"\n\n";
              msg += "Change " + Fields[i] + " from : " + frm.elements[Fields[i]].value + " to : " + getXMLValue(xmldom,Fields[i]) +"\n\n";
            }
          } else {
            if (msg != "") {msg += ", "}
            msg += Fields[i];          
          }
        }
      }
    }
    
    //  20031220 hmw Check to see if we have options passed in for no warning
    //
    if (Options) {msg=""}
              

    //  If there are fields that need to be over written then prompt the user to confirm
    //
    if (msg != "") {
      if (!confirm("The following peices of information are different :\n\n" + msg + "Do you want to overwrite these values from the ones in the database?")) {
				//	determine which field we ar ein and reset its value and select it
				//
				for (var i=0;i<frm.length;i++) {
					if (frm[i].value == RecordID && frm[i].getAttribute("onChange") !="") {
						var old=frm[i].defaultValue;
						//alert(frm[i].value);
						frm[i].value=old;
						if (frm[i].type=="text") {frm[i].select()}
						return false;
					}						
				}
      }     
    }
                
    //  Loop thour the field list and if a field exists on the form
    //  set the value to the corresponding value in the XML stream if there is one
    //
    for (i=0; i<Fields.length; i++) {
      if (frm.elements[Fields[i]]!=null) {
        //if (xmldom.selectSingleNode("//" + Fields[i])) {
        if(getXMLNode(xmldom, Fields[i])){
					// 2008-10-14 mwdo If we are changing a combo box
					//
					if(Query.indexOf('cbo:')!=-1){
					  var codelist = null;
					  try{
						  codelist = xmldom.selectNodes("//" + Fields[i] + "/codelist");
						}catch(e){
						  codelist = getXMLNode(xmldom, Fields[i]).childNodes;
						}
          
						//frm(Fields[i]).options.length=0;
						frm.elements[Fields[i]].options.length = 0;
						for(v=0;v<codelist.length;v++){
							try{
							  frm(Fields[i]).options[v]=new Option(codelist[v].selectSingleNode("Description").text, codelist[v].selectSingleNode("Code").text, false, false);
							//frm(Fields[i]).options[v]=new Option(getXMLValue(codelist[v],"Description"), getXMLValue(codelist[v],"Code"), false, false);
							}catch(e){
							  frm.elements[Fields[i]].options[v]=new Option(getXMLValue(codelist[v],"Description"), getXMLValue(codelist[v],"Code"), false, false);
							}
							//alert(getXMLValue(codelist[v],"Description")+'|'+getXMLValue(codelist[v],"Code"));
						}
						//if(frm(Fields[i]).options.length==0){
						if(frm.elements[Fields[i]].options.length==0){
							frm.elements[Fields[i]].options[v]=new Option('', '', false, false);
						}
							
					}else{
          				//frm(Fields[i]).value=xmldom.selectSingleNode("//" + Fields[i]).text ;
          				frm.elements[Fields[i]].value=getXMLValue(xmldom,Fields[i]);
					}
          //  If the field has an OnChange Event, Fire it
          //
          if (frm.elements[Fields[i]].getAttribute("onChange")) {
            //frm(Fields[i]).onchange();
            frm.elements[Fields[i]].onchange();
          }
        }
        else {
          //frm(Fields[i]).value="";
          frm.elements[Fields[i]].value="";
          if (frm.elements[Fields[i]].getAttribute("onChange")) {
            //frm(Fields[i]).onchange();
            frm.elements[Fields[i]].onchange();
          }
        }
      }
    }
    return true;
  }
  
}

function getXMLValue(obj, NodeName) {
//
//	This function returns the value of an XML node
//	Using Try Catch to deal with cross browser issues
//
var NodeValue = ""

  try 
  {
    NodeValue = obj.selectSingleNode("//" + NodeName).text;
  }
  catch(e) 
  {
    try
    {
      NodeValue = obj.getElementsByTagName(NodeName)[0].childNodes[0].nodeValue;
    }
    catch(e) 
    {
    }
  }
	
	return NodeValue;


}

function getXMLNode(obj, NodeName) {
//
//	This function returns the XML node
//	Using Try Catch to deal with cross browser issues
//
  var Node = null;

  try 
  {
    Node = obj.selectSingleNode("//" + NodeName);
  }
  catch(e) 
  {
    try
    {
      Node = obj.getElementsByTagName(NodeName)[0];
    }
    catch(e) 
    {
    }
  }
	
	return Node;


}


/*
/***************************************
	Asset Manager Required Functions
***************************************/
function modalDialogShow_IE(url,width,height) //IE
	{
	return window.showModalDialog(url,window,
		"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Raised;center:Yes;help:No;Resizable:Yes;Maximize:Yes");
	}
function modalDialogShow_Moz(url,width,height) //Moz
    {
    var left = screen.availWidth/2 - width/2;
    var top = screen.availHeight/2 - height/2;
    activeModalWin = window.open(url, "", "width="+width+"px,height="+height+",left="+left+",top="+top);
    window.onfocus = function(){if (activeModalWin.closed == false){activeModalWin.focus();};};
    }
var sActiveAssetInput;
function setAssetValue(v) //required by the asset manager
    {
		// check for a null, if so, don't set value
		v=v+"";
		if(v!=""){
    	document.getElementById(sActiveAssetInput).value = v;
		}
    }
function openAsset(s, URL){
	sActiveAssetInput = s 
	
	// grab current value and get folder path out of it
	if(document.getElementById(sActiveAssetInput).value!=""){
		currentVal = new String(document.getElementById(sActiveAssetInput).value);
		LastSlash = currentVal.lastIndexOf("/");
		LastSlash = LastSlash+1;
		currentFolder = currentVal.substring(0, LastSlash);
	}else{
		currentFolder = "";
	}
	
	if(navigator.appName.indexOf('Microsoft')!=-1){
		
		rtnVal=modalDialogShow_IE(URL+"?folder="+currentFolder,640,465); //IE	
		
		// if value returned is not null, set value
		rtnVal=rtnVal+"";
		if(rtnVal!=""){
			document.getElementById(sActiveAssetInput).value=rtnVal;
		}
	}else{
		modalDialogShow_Moz(URL+"?Folder="+currentFolder,640,465); //Moz	
	}
}
/*****************************************/
