/* Copyright (c) 2009 River & Dock Limited . All rights reserved. */

/* ********************************************************
Set of JavaScript functions used throughout the database

JavaScript Validation 

Version History:

  Version 		Name			              	Date					Modification
  1.0			Alastair Grant (AG)				Release Date			Created

********************************************************* */

function spin(id,status){
	var  spinner= '<img class="noborder" src="asset/img/global/wait-circle.gif" border=0>';
	if (status==true){
	document.getElementById(id).innerHTML = spinner
	}else{
		$(id).innerHTML = ''
	}
}

function doLogin() { 
s = document.location.search; 

/* Check '&Login' not already in URL! */
if (s.toLowerCase().indexOf("&login") == 
-1 ) { 
/* Check that there is a '?Open' part to append to */
a = (s==="") ? "?Open&Login" : "&Login"; 
document.location.href += a; 
}
}

function doLogout(nabpath,id,url){ 
        if (nabpath == ''){ 
         nabpath = 'names.nsf' 
        } 

var logoutpath = '/'+ nabpath + '?Logout'; 

new Ajax.Request(logoutpath, { 
 method: 'post', 
 onSuccess: function(originalRequest) { 
                                 processLogout(originalRequest,id,url); 
  } 
}); 
}; 

function processLogout(originalRequest,id,url){ 
/* 
id = the div id that we should update 
url = if passed this is where we go to 
*/ 
        var notice = $(id); 
           notice.update('You have now logged out. ' + "<a href='Javascript:doLogin()'>(>>Login)</a>").setStyle({ background: '#fdd' }); 
      if (url !==''){ 
      location.href = url; 
      }       
} 


function doPrint() { 
s = document.location.search; 

/* Check '&action=print' not already in URL */
if (s.toLowerCase().indexOf("&action=print") == 
-1 ) { 
/* Check that there is a '?Open' part to append to */
a = (s==="") ? "?OpenDocument&action=print" : "&action=print"; 
document.location.href += a; 
}
}


function doDelete() {
	if ( confirm('Are you sure you want to delete this document?') ){
		location.search = "?DeleteDocument";
	}
}

 
function doClear(theText) {
     if (theText.value == theText.defaultValue) {
         theText.value = "";
     }
 }

/*
mailto replaces the mailto:
anchor link and prevents
spambots harvesting the 
address.
*/

function mailto(name, domain)
{
 location.href = "mailto:" + name + "@" + domain;
}

function openDbRelativeURL( url, target ){
/* Check we have a target window */
target = (target === null ) ? window : target;
 /* Work out the path of the database */
path = location.pathname.split('.nsf')[0] + '.nsf/';
target.location.href = path + url;
}
 

function changecolor(fld,event){  // changes color of field
	if (event ==1) { // entering
		fld.style.color='black'; //changes text color
		fld.style.backgroundColor = '#a6D4f4'; //changes background lgrey
	}
	if (event ==2) { // entering
		fld.style.color='#000'; //changes text color
		fld.style.backgroundColor = '#fff'; //changes background
	}
}
 

function trim(aStr) {
	return aStr.replace(/^\s{1,}/, "").replace(/\s{1,}$/, "");
}



/* function to replace the 'No documents found' message */
function checkEmpty()
{ 
if (document.getElementById("viewBody").innerHTML.indexOf("No documents found") > 0) 
{
document.getElementById("viewBody").style.display = 'none';
document.getElementById("emptyView").style.display = 'inline';
} 
else
{
document.getElementById("viewBody").style.display = 'inline';
document.getElementById("emptyView").style.display = 'none';
} 

}

function getWWW(v1,v2){
window.location ="http://www." + v1 + v2;
}

function openWWW(v1,v2,title,params){
window.open("http://www." + v1 + v2,title,params);
}

function openWin(url,name,l,t,w,h,args){
                /* Get the screen's dimensions */
                var x=screen.width, y=screen.height;
                /* If the popup window is larger than the screen, make it smaller */
                if(w>x-50){w=x-50;}
                if(h>y-50){h=y-50;}
                /* If left and top are null, set them so the window opens center screen */
                if(!l){l=(x-w)/2;}
                if(!t){t=(y-h)/5;}
                var win=window.open(url,name,'left='+l+',top='+t+',width='+w+',height='+h+','+args);
                win.focus();
} 

/* set option value */
function setVals(oo,textorvalue,valuetoset) {
str = valuetoset;
for (i=0; i<oo.options.length; i++) {
if (oo.options[i].value == str) {
oo.selectedIndex = i;
}
}
}

 function loadcorners(rad,vTags,id)
  {
      /*
      curvycorners
      The new 'validTags' setting is optional and allows
      you to specify other HTML elements that curvyCorners
      can attempt to round.

      The value is comma separated list of html elements
      in lowercase.

      validTags: ["div", "form"] // passed as vTags parameter

      The above example would enable curvyCorners on FORM elements.
      */
      settings = {
          tl: { radius: rad},
          tr: { radius: rad},
          bl: { radius: rad},
          br: { radius: rad},
          antiAlias: true,
          autoPad: true,
          validTags: [vTags]
      };

      /*
      Usage:
	 passed as the 'id' variable
      newCornersObj = new curvyCorners(settingsObj, classNameStr);
      newCornersObj = new curvyCorners(settingsObj, divObj1[, divObj2[, divObj3[, . . . [, divObjN]]]]);
      */
      var myBoxObject = new curvyCorners(settings, id);
      myBoxObject.applyCornersToAll();
  }

function doAltRow(str,css,cssalt)
  {
      /*
      Alastair Grant
      Get the last value of id after '_' then convert to a number divide by 2 and if odd no color if even write color.
      Uses standardstyles.css
      */
      p = str.lastIndexOf("_");
      x = str.substring(p+1);
      
   
	/* now divide by 2 to split the odds and evens */
	y = parseInt(x) / 2 ;
     // get the modulus: if it's 0, then it's an integer
        var myMod = y % 1;

         if (myMod == 0) {
		      colour = css;
         } else {
		      colour = cssalt;
         }

	// return as an object with 2 properties
	return {pos : x, css : colour};

     }

function doOpenPage(link,pg)
  {
    var a = link.href.split('?'); 
    document.location.href = a[0] +'?'+ pg
  }


function doCountPerPage(url,count)
  {
  	
      /*
	Changes the count per page in the url.
      */
      str = url.search;
      countstart = str.toLowerCase().indexOf('&count=');
      countend = str.toLowerCase().indexOf('&',countstart+7);
      
     if (count == '0' || count ==''){ count = 10};

	/* Check '&count' not in URL*/
	if (countstart == -1 ) { 
	/*	no count so just append */
	document.location.search += '&count=' + count; 
	}  else {
	// search and replace /

	startstr = str.slice(0,countstart +7);

	  if (countend == -1){ 
		endstr = ''
		}else{
		endstr = str.slice(countend );	
		};
	}    
	output = startstr + count + endstr;
	document.location.search = output;  
  }


/* Function to get an object given its id */

function getId(id) {     
        if (document.getElementById && document.getElementById(id)) { 
                return document.getElementById(id); } 
        
        else if (document.all && document.all(id)) { 
          return document.all(id); } 
        
        else if (document.layers && document.layers[id]) { 
                return document.layers[id]; } 
        
        else { return false; } 
} 

/* Gets the value of a named parameter in the query string */
function readQueryString(param) { 
 var loca = document.location.href; 
 if(loca.indexOf('?' + param + '=')>-1 || loca.indexOf('&' + param + '=')>-1) { 
  var qstring = loca.split('?'); 
  var keyVal = qstring[1].split('&'); 
  
        for (var i=0; i < keyVal.length; i++) { 
   if(keyVal[i].indexOf(param + '=')==0) { 
    var val = keyVal[i].split('='); 
    return val[1]; } 
  }         
  
        return false; } 
        
 else { return false; } 

} 

function addBookmark() {

                if( window.sidebar && window.sidebar.addPanel ) {

                                 //Gecko (Netscape 6 etc.) - add to Sidebar

                                 window.sidebar.addPanel( document.title, location.href, '' );

                } else if( window.external && ( navigator.platform == 'Win32' ||

                                                  ( window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1 ) ) ) {

                                 //IE Win32 or iCab - checking for AddFavorite produces errors in

                                 //IE for no good reason, so I use a platform and browser detect.

                                 //adds the current page page as a favourite; if this is unwanted,

                                 //simply write the desired page in here instead of 'location.href'

                                 window.external.AddFavorite( location.href, document.title );

                } else if( window.opera && window.print ) {

                                 //Opera 6+ - add as sidebar panel to Hotlist

                                 return true;

                } else if( document.layers ) {

                                 //NS4 & Escape - tell them how to add a bookmark quickly (adds current page,

                                 //not target page)

                                 alert( 'Please click OK then press Ctrl+D to create a bookmark' );

                } else {

                                 //other browsers - tell them to add a bookmark (adds current page, not target page)

                                 alert( 'Please use your browser\'s bookmarking facility to create a bookmark' );

                }

                return false;

}

function getbrowserwidth(){

                if (navigator.userAgent.indexOf("MSIE") > 0)

                                 return(document.body.clientWidth);

                else

                                 return window.outerWidth;

}



function getbrowserheight(){

                if (navigator.userAgent.indexOf("MSIE") > 0)

                                 return(document.body.clientHeight);

                else

                                 return window.outerHeight;

}





function doCompareDates(x,y,op) {
        var d1 = doYYYYMMDD(x);
        var d2 = doYYYYMMDD(y);
        if (op =='1'){
            if (d1 > d2){
                return true;    
            }else{
                return false;
            }
        };
        if (op =='2'){
            if (d1 < d2){
                return true;    
            }else{
                return false;
            }
        }
        if (op =='3'){
            if (d1 == d2){
                return true;    
            }else{
                return false;
            }
        }
}

function doYYYYMMDD(dateString,format) {
        /* assumes US format - so switch to if not */
        if (format=='dmy'){
            var dateAr=dateString.split('/');
            dateString = dateAr[1]+'/'+dateAr[0]+'/'+dateAr[2];
        }
        var d = new Date(dateString);
        yyyy = (d.getFullYear()).toString();
        mm = "00" +((d.getMonth()+1)).toString();
        dd = "00" + (d.getDate()).toString();
        mm = sRight(mm,2);
        dd = sRight(dd,2);
        var yyyymmdd = yyyy + mm + dd;
        return yyyymmdd;
}

    function sLeft(str, n){
        if (n <= 0)
            return "";
        else if (n > String(str).length)
            return str;
        else
            return String(str).substring(0,n);
        }
        
        
    function sRight(str, n){
        if (n <= 0)
            return "";
        else if (n > String(str).length)
            return str;
        else {
            var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
        }
    }