/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Copyright Cylo.co.uk
Written by Graham Vincent 
Contact :: loudsphiers@gmail.com
*/
///<FILE name='dialog.js' url='/csp/v2/app/lib/dialog.js'>
///<description>
///The JavaScript facilitates the modal dialog used throughout the intellect system.
///</description>
CyloDialog = new Object();
CyloDialog.isConfOpen = false;
CyloDialog.imagePath="../img/";//relative to this js file if this file is being included in the normal way
CyloDialog.confFlashIndicator="off";
CyloDialog.CyloInterval="";
CyloDialog.extra_Top=0;
CyloDialog.extra_Left=0;
CyloDialog.saveCurrentConfParams=false;
CyloDialog.currentConfParams = new Array();
CyloDialog.currentFX = "";

CyloDialog.OKConfirmation = function(words,code,text,size,title,img,fx)
{
 try
 {
  if(!title)
  {
   title = "Confirmation";
  }
  if(code.indexOf("SELF_CLOSE") > -1)
  { 
   code = CyloDialog.replaceAll(code,"SELF_CLOSE","CyloDialog.closeConf();");
  }
  buttons = "<input class='Mybutton' type='submit' id='okConfButton' value='"+text+"' onclick='"+code+"' />";
  CyloDialog.centerObjectOnPage(words,title,buttons,size,img,'okConfButton',fx);
  CyloDialog.isConfOpen=true;
 }catch(e)
 {
  alert(e.message + " in CyloDialog.OKConfirmation");
  return false;
 }
}
CyloDialog.yesNoConfirmation = function(words,pos,neg,pos_t,neg_t,size,title,img,fx) 
{
	//words = content | 
	//pos = code to execute on first button | 
	//neg = second button | 
	//pos_t is text of fiorst button | 
	//neg_t = second text for button
	//size = small medium large landscape skyscraper interface_small interface_medium
	//img = 1 - 5 Integer (icons showned in top left hand corner)
 try
 {
  if(!title)
  {
   title = "Respond";
  }
  if(neg.indexOf("SELF_CLOSE") > -1)
  { 
   neg = CyloDialog.replaceAll(neg,"SELF_CLOSE","CyloDialog.closeConf();");
  }
  if(pos.indexOf("SELF_CLOSE") > -1)
  { 
   pos = CyloDialog.replaceAll(pos,"SELF_CLOSE","CyloDialog.closeConf();");
  }
  buttons = "<input class='Mybutton' type='submit' id='yesConfButton' value='"+pos_t+"' onclick='"+pos+"' /> &nbsp; <input class='Mybutton' type='submit' id='noConfButton' value='"+neg_t+"' onclick='"+neg+"' />";
  CyloDialog.centerObjectOnPage(words,title,buttons,size,img,'yesConfButton',fx);
  CyloDialog.isConfOpen=true;
 }catch(e)
 {
  alert(e.message + " in CyloDialog.yesNoConfirmation");
  return false;
 }
}

CyloDialog.closeConf = function()
{
 try
 {
  CyloDialog.unmakeWindowModelMode();
  if(CyloDialog.$("CyloConfBox"))
  CyloDialog.$("CyloConfBox").parentNode.removeChild(CyloDialog.$("CyloConfBox"));
  CyloDialog.isConfOpen=false;
  window.clearInterval(CyloDialog.CyloInterval);
  return 0;
 }catch(e)
 {
  alert(e.message + " in CyloDialog.closeConf");
  return false;
 }
}

CyloDialog.unmakeWindowModelMode = function(removeChildren)
{ 
 try
 {
  if(CyloDialog.$("invisModalTable"))
  {
   CyloDialog.$("invisModalTable").parentNode.removeChild(CyloDialog.$("invisModalTable"));
  }
 
  if(CyloDialog.$("invisModal"))
  {
   CyloDialog.$("invisModal").parentNode.removeChild(CyloDialog.$("invisModal"));
  }
  CyloDialog.unhookEvent('invisModalTable', 'mousewheel', CyloDialog.cancelEvent);//attach the mouse wheel event tot he table and cancel it
 }catch(e)
 {
  alert(e.message + " in CyloDialog.unmakeWindowModelMode");
  return false;
 }
}

CyloDialog.showPreviouseConf=function()
{
 try
 {
  CyloDialog.centerObjectOnPage(CyloDialog.currentConfParams["words"],CyloDialog.currentConfParams["title"],CyloDialog.currentConfParams["buttons"],CyloDialog.currentConfParams["size"],CyloDialog.currentConfParams["img"],CyloDialog.currentConfParams["idforinitfocus"]);
 }catch(e)
 {
  alert(e.message + " in CyloDialog.showPreviouseConf");
  return false;
 }
}

CyloDialog.centerObjectOnPage=function(words,title,buttons,size,img,idforinitfocus,fx)
{
 try
 {
  try
  {
   //close any open tooltips
   UnTip();
  }catch(e)
  {
   //no need to flag, just means tooltip script is not avaliable
  }
  //if(CyloDialog.saveCurrentConfParams==true)
  //{
   CyloDialog.currentConfParams["words"]=words;
   CyloDialog.currentConfParams["title"]=title;
   CyloDialog.currentConfParams["buttons"]=buttons;
   CyloDialog.currentConfParams["size"]=size;
   CyloDialog.currentConfParams["img"]=img;
   CyloDialog.currentConfParams["idforinitfocus"]=idforinitfocus;
   CyloDialog.currentConfParams["fx"]=fx;
   CyloDialog.saveCurrentConfParams = false;
  //}
  fx=CyloDialog.$get(fx,"");
  CyloDialog.currentFX = fx;
  if(CyloDialog.isConfOpen==true)CyloDialog.closeConf();//close any open confirmations
  img = CyloDialog.getConfImage(img);
  
  CyloDialog.makeWindowModelMode(true);
  words = "<div id='tempdivholderconf'style='filter:Alpha(opacity=100);'><table id='confBoxInner' class='CyloConfBoxTop' cellpadding='3' cellspacing='0' onMouseDown='CyloDialog.drag(this.parentNode.parentNode,event);'><tr valign='middle'><td class='CyloConfBoxTitle' id='confIconId'><img src='"+img+"' /></td><td class='CyloConfBoxTitle' id='confTitleId' width='99%'>"+title+"</td></tr></table><table id='confBoxInnerLower' class='CyloConfBoxBottom' cellpadding='3' cellspacing='0' ><tr><td class='CyloConfBoxBody' id='confBoxBody'>"+words+"</td></tr><tr><td class='CyloConfBoxButtons'>"+buttons+"</td></tr></table></div>";
  
  el = document.createElement("div");
  el.innerHTML = words;
  el.style.position = 'absolute';
  el.id="CyloConfBox";
  window.onresize=CyloDialog.makeWindowModelMode;
  document.body.appendChild(el);
  var w=0;
  var h=0;
  if(size.indexOf("/")>-1)
  {
   size=size.split("/");
   w=size[0];
   h=size[1];
   size="specified";
  }
  switch(size)
  {
   case "specified":   CyloDialog.$("tempdivholderconf").style.width=w;CyloDialog.$("confBoxInner").style.width=w;CyloDialog.$("confBoxInnerLower").style.width=w;CyloDialog.$("confBoxBody").style.height=h;break;
   case "small":   CyloDialog.$("tempdivholderconf").style.width=300;CyloDialog.$("confBoxInner").style.width=300;CyloDialog.$("confBoxBody").style.height=100;;break;
   case "medium":   CyloDialog.$("tempdivholderconf").style.width=400;CyloDialog.$("confBoxInner").style.width=400;CyloDialog.$("confBoxInnerLower").style.width=400;CyloDialog.$("confBoxBody").style.height=400;break;
   case "dcsdia":   CyloDialog.$("tempdivholderconf").style.width=500;CyloDialog.$("confBoxInner").style.width=500;CyloDialog.$("confBoxInnerLower").style.width=500;CyloDialog.$("confBoxBody").style.height=100;break;
   case "large":   CyloDialog.$("tempdivholderconf").style.width=500;CyloDialog.$("confBoxInner").style.width=500;CyloDialog.$("confBoxInnerLower").style.width=500;CyloDialog.$("confBoxBody").style.height=500;break;
   case "landscape":  CyloDialog.$("tempdivholderconf").style.width=800;CyloDialog.$("confBoxInner").style.width=800;CyloDialog.$("confBoxInnerLower").style.width=800;CyloDialog.$("confBoxBody").style.height=100;break;
   case "skyscraper":  CyloDialog.$("tempdivholderconf").style.width=200;CyloDialog.$("confBoxInner").style.width=200;CyloDialog.$("confBoxInnerLower").style.width=200;CyloDialog.$("confBoxBody").style.height=550;break;
   case "interface_small": CyloDialog.$("tempdivholderconf").style.width=370;CyloDialog.$("confBoxInner").style.width=370;CyloDialog.$("confBoxInnerLower").style.width=370;CyloDialog.$("confBoxBody").style.textAlign="left";break;
   case "interface_medium":CyloDialog.$("tempdivholderconf").style.width=400;CyloDialog.$("confBoxInner").style.width=400;CyloDialog.$("confBoxInnerLower").style.width=400;CyloDialog.$("confBoxBody").style.height=400;CyloDialog.$("confBoxBody").style.textAlign="left";break;
  }
  var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
  var leftOffset = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
  var brSize = CyloDialog.getBrowserSize();
  var bodyWidth = brSize[0];
  var bodyHeight = brSize[1];
  var tmpWidth = el.offsetWidth; 
  var tmpHeight = el.offsetHeight;
  el.style.left = (Math.ceil((bodyWidth - tmpWidth) / 2) + leftOffset)+ 'px';
  el.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';
  el.zIndex = 999999;
  //CyloDialog.CyloInterval = window.setInterval("CyloDialog.centerConf()","10");
  CyloDialog.$(idforinitfocus).focus();//set focus to the first button so user can press space bar or return..
 }catch(e)
 {
  alert(e.message + " in CyloDialog.centerObjectOnPage");
  return false;
 }
}

CyloDialog.centerConf=function()
{
 try
 {
  el = CyloDialog.$("CyloConfBox");
  var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
  var brSize = CyloDialog.getBrowserSize();
  var bodyWidth = brSize[0];
  var bodyHeight = brSize[1];
  var tmpWidth = el.offsetWidth; 
  var tmpHeight = el.offsetHeight;
  //el.style.left = CyloDialog.extra_Left + tmpWidth+ 'px';
  //el.style.top = CyloDialog.extra_Top + tmpHeight + 'px';
  el.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + (CyloDialog.extra_Left / 2)+ 'px';
  el.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) + (CyloDialog.extra_Top / 2)+  topOffset) + 'px';
 }catch(e)
 {
  alert(e.message + " in CyloDialog.centerConf");
  return false;
 }
}

CyloDialog.makeWindowModelMode=function(run)
{
	try
	{
		if(typeof(run)=="undefined")
		{
			run=false;
		}
		if(CyloDialog.isConfOpen==true)
		{
			var testLayer=document.getElementById("invisModal");
			testLayer.style.width="100%";
			testLayer.style.height="100%";
			var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
			var leftOffset = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
			var brSize = CyloDialog.getBrowserSize();
			var bodyWidth = brSize[0];
			var bodyHeight = brSize[1];
			var tCyloConfBox=document.getElementById("CyloConfBox");
			var tmpWidth = tCyloConfBox.offsetWidth; 
			var tmpHeight = tCyloConfBox.offsetHeight;
			tCyloConfBox.style.left = (Math.ceil((bodyWidth - tmpWidth) / 2) + leftOffset)+ 'px';
			tCyloConfBox.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';
			return;
		}
		if(run==false)return;
		var brSize = CyloDialog.getBrowserSize();
		var bodyWidth = brSize[0];
		var bodyHeight = brSize[1];
		var width = bodyWidth+"px";//ok for ie
		if(self.innerHeight)
		{
		width = "100%";//ok for ie
		}
		var hidspan=document.createElement("div");
		hidspan.id="invisModal";
		hidspan.onclick=new Function("CyloDialog.flashConf();");
		hidspan.zIndex = 1000;
		firstChildOfDoc=document.getElementsByTagName("body");
		hidspan.style.backgroundColor="black";
		try
		{
		hidspan.style.opacity = (0 / 100);
		hidspan.style.MozOpacity = (0 / 100);
		hidspan.style.KhtmlOpacity = (0 / 100);
		hidspan.style.filter = "alpha(opacity=" + 20 + ")";
		}
		catch (e)
		{
		}
		firstChildOfDoc[0].appendChild(hidspan);
		hidspan.style.position="absolute";
		hidspan.style.top="0px";
		hidspan.style.left="0px";
		hidspan.className="CyloHidspan";
		hidspan.style.width=document.body.scrollWidth + "px";
		hidspan.style.height=document.body.scrollHeight + "px";
		CyloDialog.hookEvent('invisModalTable', 'mousewheel', CyloDialog.cancelEvent);//attach the mouse wheel event to the table and cancel it
	}catch(e)
	{
		alert(e.message + " in CyloDialog.makeWindowModelMode");
		return false;
	}
}

CyloDialog.getConfImage = function(i)
{
 try
 {
  if(typeof(i)=="undefined" || i=="")i=1;
  /*
   1 = Alert
   2 = Info
   3 = Error
   4 = Key
   5 = Lock
  */
  try
  {
   i = parseInt(i);
  }
  catch (e)
  {
   return CyloDialog.imagePath + "alert.gif";
  }
  switch(i)
  {
   case 1: case "1":return CyloDialog.imagePath + "alert.gif";break;
   case 2: case "2":return CyloDialog.imagePath + "info.gif";break;
   case 3: case "3":return CyloDialog.imagePath + "error.gif";break;
   case 4: case "4":return CyloDialog.imagePath + "key.gif";break;
   case 5: case "5":return CyloDialog.imagePath + "lock.gif";break;
  }
  return CyloDialog.imagePath + "alert.gif";
 }catch(e)
 {
  alert(e.message + " in CyloDialog.getConfImage");
  return false;
 }
}

CyloDialog.flashConf = function()
{
 try
 {
  setTimeout("CyloDialog.flashHelper(0)",1);
  CyloDialog.$(CyloDialog.currentConfParams["idforinitfocus"]).focus();//reset focus to first button
 }catch(e)
 {
  alert(e.message + " in CyloDialog.flashConf");
  return false;
 }
}

CyloDialog.flashHelper = function(times)
{
 try
 {
  times++;
  if(times<7)
  {
   if(CyloDialog.confFlashIndicator=="off")
   {
    CyloDialog.confFlashIndicator="on";
    if(CyloDialog.$("confTitleId"))
    {
     CyloDialog.className(CyloDialog.$("confTitleId"),"CyloConfBoxTitleFlashOn",true);
     CyloDialog.className(CyloDialog.$("confIconId"),"CyloConfBoxTitleFlashOn",true);
    }
   }else{
    CyloDialog.confFlashIndicator="off";
    if(CyloDialog.$("confTitleId"))
    {
     CyloDialog.className(CyloDialog.$("confTitleId"),"CyloConfBoxTitleFlashOn",false);
     CyloDialog.className(CyloDialog.$("confIconId"),"CyloConfBoxTitleFlashOn",false);
    }
   }
  setTimeout("CyloDialog.flashHelper("+times+")",80);
 }
 }catch(e)
 {
  alert(e.message + " in CyloDialog.flashHelper");
  return false;
 }
}
CyloDialog.drag = function(elementToDrag,event)
{
 try
 {
  var brSize = CyloDialog.getBrowserSize();
  var bodyWidth = brSize[0];
  var bodyHeight = brSize[1];
  
  var startX = event.clientX, startY=event.clientY;
  var origX = elementToDrag.offsetLeft, origY=elementToDrag.offsetTop;
  var dX = startX - origX; var dY = startY - origY;
  elementToDrag.setCapture();
  elementToDrag.attachEvent("onmousemove",moveHandler);
  elementToDrag.attachEvent("onmouseup",upHandler);
  elementToDrag.attachEvent("onlosecapture",upHandler);
  event.cancelBubble = true;
  event.returnValue = false;
  function moveHandler(e)
  {
   e=window.event;
   //Stop the alert being dragged of screen
   if((e.clientX - dX) < (bodyWidth - 100) && (e.clientX - dX) > 1)
   {
    elementToDrag.style.left = (e.clientX - dX) + "px";
    CyloDialog.extra_Left = (e.clientX - dX);
   }
   if((e.clientY - dY) < (bodyHeight - 100) && (e.clientY - dY) > 1)
   {
    elementToDrag.style.top = (e.clientY - dY) + "px"; 
    CyloDialog.extra_Top = (e.clientY - dY);
   }
   e. cancelBubble = true;
  }
  function upHandler(e)
  {
   e=window.event;   
   elementToDrag.detachEvent("onmousemove",moveHandler);
   elementToDrag.detachEvent("onmouseup",upHandler);
   elementToDrag.detachEvent("onlosecapture",upHandler);  
   elementToDrag.releaseCapture();
   e.cancelBubble = true; 
  }
 }
 catch (e)
 { alert(e.message)
 }
}

CyloDialog.replaceAll=function(str,from,to)
{ 
 try
 {
  var idx = str.indexOf( from ); while ( idx > -1 ) { str = str.replace( from, to ); idx = str.indexOf( from );}
  return str;
 }catch(e)
 {
  alert(e.message + " in _CyloDialog.replaceAll");
  return false;
 }
}

CyloDialog.$=function()
{
 try
 {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++)
  {
   var element = arguments[i];
   if (typeof element == 'string')
    try{element = document.getElementById(element);}catch(e){}
   if (arguments.length == 1)
    return element;
   elements.push(element);
  }
  return elements;
 }catch(e)
 {
  alert(e.message + " in _CyloDialog.(s) $");
  return false;
 }
}

CyloDialog.hookEvent = function(element, eventName, callback)
{
 try
 {
  if(typeof(element) == "string")
   element = document.getElementById(element);
  if(element == null)
   return;
  if(element.addEventListener)
  {
   if(eventName == 'mousewheel')
   {
    element.addEventListener('DOMMouseScroll', 
    callback, false);  
   }
   element.addEventListener(eventName, callback, false);
  }
  else if(element.attachEvent)
   element.attachEvent("on" + eventName, callback);
 }catch(e)
 {
  alert(e.message + " in _CyloDialog.hookEvent");
  return false;
 }
}

CyloDialog.unhookEvent = function(element, eventName, callback)
{
 try
 {
  if(typeof(element) == "string")
   element = document.getElementById(element);
  if(element == null)
   return;
  if(element.removeEventListener)
  {
   if(eventName == 'mousewheel')
   {
   element.removeEventListener('DOMMouseScroll', 
   callback, false);  
   }
   element.removeEventListener(eventName, callback, false);
  }
  else if(element.detachEvent)
   element.detachEvent("on" + eventName, callback);
 }catch(e)
 {
  alert(e.message + " in _CyloDialog.unhookEvent");
  return false;
 }
}

CyloDialog.$get = function(v,d)
{
 if(typeof(v)=="undefined" || v=="")v="";
 if(typeof(d)=="undefined" || d=="")return v;
 return d;
}


CyloDialog.getBrowserSize = function()
{
 try
 {
  var bodyWidth = document.documentElement.clientWidth;
  var bodyHeight = document.documentElement.clientHeight;
  
  var bodyWidth, bodyHeight; 
  if (self.innerHeight){ // all except Explorer 
   
     bodyWidth = self.innerWidth; 
     bodyHeight = self.innerHeight; 
  }  else if (document.documentElement && document.documentElement.clientHeight) {
     // Explorer 6 Strict Mode    
     bodyWidth = document.documentElement.clientWidth; 
     bodyHeight = document.documentElement.clientHeight; 
  } else if (document.body) {// other Explorers    
     bodyWidth = document.body.clientWidth; 
     bodyHeight = document.body.clientHeight; 
  } 
  return [bodyWidth,bodyHeight];  
 }catch(e)
 {
  alert(e.message + " in _CyloDialog.getBrowserSize");
  return false;
 }
}



CyloDialog.className = function(el,className,bool)
{
 try
 {
  var cn=el.className;
  if(bool==true)
  {
   if(typeof(cn)=="undefined" || cn=="")
   {
    el.className=className;
   }else{
    el.className=CyloDialog.trim(cn + " " +className);
   }
  }else{
   cn=" "+cn+" ";
   cn=this.replaceAll(cn," "+className+" "," ");
   el.className=CyloDialog.trim(cn);
  }
 }catch(e)
 {
  alert(e.message + " in _CyloDialog.className");
  return false;
 }
}

CyloDialog.trim=function(value)
{
 try
 {
 function LTrim( value )
 {
  var re = /\s*((\S+\s*)*)/;
  return value.replace(re, "$1");
 }
 function RTrim( value )
 {
  var re = /((\s*\S+)*)\s*/;
  return value.replace(re, "$1");
 }
 return LTrim(RTrim(value));
 }catch(e)
 {
 alert(e.message + " in _CyloDialog.trim");
 return false;
 }
}
///</FILE>