/*
* son of suckerfish menu script from:
* http://www.htmldog.com/articles/suckerfish/dropdowns/
*/
sfHover = function() {
   for(var j = 0; j < 200; j++){
      if (document.getElementById("nav_"+j) != null) {
         var sfEls = document.getElementById("nav_"+j).getElementsByTagName("LI");
         for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmouseover=function() {
               this.className+=" sfhover";
               this.style.zIndex=200; /*this line added to force flyout to be above relatively positioned stuff in IE*/
            }
            sfEls[i].onmouseout=function() {
               this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
            }
         }
      }
   }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

/**
* Pull the file name and path from a string
*
* Parse a string and pull out the file's path, name, and extention
*
* @requires    xtractFileNameAndExt
* @param       string   The path to parse. Ex: /User/Shared/myFile.pdf
* @returns     string   Javascript object array. Ex: {path: '/User/Shared/', file: 'myFile', ext: 'pdf'}
*/
function xtractFileNameAndPath(data){
   var m = data.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
   if (m == null) {
      var fileName = data;
      var filePath = '';
   }else {
      var fileName = m[2];
      var filePath = m[1];
   }
   var f = xtractFileNameAndExt(fileName);
   return {path: filePath, file: f['filename'], ext: f['ext']}
}
/**
* Pull the file name and extention from a string
*
* @param    string   The path to parse. Ex: myFile.pdf
* @returns  string   Javascript object array. Ex: {filename: 'myFile', ext: 'pdf'}
*/
function xtractFileNameAndExt(data){
   data = data.replace(/^\s|\s$/g, ""); //trims string
   
   if (/\.\w+$/.test(data)) {
       if (data.match(/([^\/\\]+)\.(\w+)$/) ){
           return {filename: RegExp.$1, ext: RegExp.$2};
       }else{
           return {filename: "", ext:null};
       }
   }else {
       if (data.match(/([^\/\\]+)$/) ){
           return {filename: RegExp.$1, ext: null};
       }else{
           return {filename: "", ext:null};
       }
   }
}
/**
* Pull the parts of a url
*
* @requires    xtractFileNameAndExt
* @param       string   The path to parse
* @returns     string   Javascript object array.
*           Ex: {
*                   url:"http://www.example.com/some/path/index.html#top",
*                   protocol:"http",
*                   host:"www.example.com",
*                   path:"/some/path/",
*                   file:"index",
*                   ext:"html",
*                   hash:"#top"
*               }
*/
function parseUrl(data) {
   var e=/^((http|https|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/;
   
   if (data.match(e)) {
      var f = xtractFileNameAndExt(RegExp.$6);
      return  {
         url: RegExp['$&'],
         protocol: RegExp.$2,
         host:RegExp.$3,
         path:RegExp.$4,
         file:f['filename'],
         ext:f['ext'],
         hash:RegExp.$7
      };
   }else {
      return  {url:"", protocol:"",host:"",path:"",file:"",ext:"",hash:""};
   }
}

/**
* Restrict an element's input to numeric values
* 
* Allows 0-9, a single ".", and a single "-" at the beginning of the string
* Usage: <input type='text' onkeypress='return restrictToNumber(this, event);'/>
* 
* @param    object   Input element we are testing, "this"
* @param    event    (optional)Key stroke event.
* @return   boolean  
*/
restrictToNumber = function(elm, e, isMoney){
    var code = '';
    if (!e) {var e = window.event;}
    if(e.keyCode) {
        code = e.keyCode;
    }else if(e.which) {
        code = e.which;
    }
    var character = String.fromCharCode(code);
    if(code == 27) {
        elm.blur();
        return false;
    }
    if((e.ctrlKey == false) && (code != 9) && (code != 8) && (code != 36) && (code != 37) && (code != 38) && (code != 39) && (code != 40)) {
        if(character.match(/[0-9\.\-]/g)){
            if(character.match(/[\.]/g)){
                if (elm.value.match(/\./i) != null){
                    return false;
                }
            }
			if(isMoney == true){
				if (elm.value.match(/([\.][\d]{2})/i) != null){
					return false;
				}
			}
            if(character.match(/[\-]/g)){// check for negative
                if (elm.value.match(/\-/i) != null){
                    return false;
                }else{ // put the - first
                    elm.value = '-'+elm.value;
                    return false;
                }
            }
            return true;
        }else{
            return false;
        }
    }
}

/**
* Test if a value is a valid number
* 
* Basically a wrapper for the double negative !isNaN()
* 
* @param    mixed   Input we are testing
* @return   boolean  
*/
isANum = function(x){
	return !isNaN(x);
}

/**
* Restrict an element's input to SQL naming standards
* 
* Allows: 	String must begin with alpha character.
* 			All other characters must be alpha numeric or underscore. 
* Usage: <input type='text' blur='restrictToSqlStandard(this);'/>
* 
* @param    object   Input element we are testing, "this"
*/
restrictToSqlStandard = function(elm){
	var elmVal = new String($(elm).value);
	
	// step one, remove digits at the begining of string
	var myReg = /^[\d]+/i;
	elmVal = elmVal.replace(myReg, new String (""));
	
	// step two, remove anything not alpha-numeric or underscore
	myReg = /([^a-zA-Z0-9_ ])/;
	elmVal = elmVal.replace(myReg, new String (""));
	
	$(elm).value = elmVal;
}

createFileTag = function(inContainer, tagId, tagName, tagClass){
	var limit = 5;
	var currentImageTags = $(inContainer).select('input');
	var tagCount = currentImageTags.length;
	if(tagCount < limit){
		var x = document.createElement('input');
		x.setAttribute('type', 'file');
		x.setAttribute('id', tagId+'_'+tagCount);
		x.setAttribute('name', tagName+'['+tagCount+']');
		x.setAttribute('class', tagClass);
		
		$(inContainer).appendChild(x);
	}else{
		alert('limit of '+limit+' has been reached');
	}
}

/**
* Get the XY position of the mouse in the browser window
* 
* ex 1 as object.
* var mousePosition = getMouseXYPosition();
* var mouseX = mousePosition.x;
* var mouseY = mousePosition.y;
*
* ex 2 cause directly.
* var mouseX = getMouseXYPosition.x;
* 
* @param@param	event	(optional)Key stroke event.
* @return 		object	JS object
*/
getMouseXYPosition = function (e){
	myMouseX=(e||event).clientX;
	myMouseY=(e||event).clientY;
	if (document.documentElement.scrollTop > 0) {
		myMouseY = myMouseY + document.documentElement.scrollTop;
	}
	return {x: myMouseX, y: myMouseY};
}

/**
* Format number to US money
* 
* @param	number	
* @return 	string	Formatted string
*/
MoneyFormat = function(amount)
{
	amount = amount.toFixed(2);
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return '$'+amount;
}

/**
* Enable or disable elements in a fieldset
*
* EX.
* 	toggleFieldsetItemEnable('cf2Fieldset_25', 'select.cf2customFieldSelectPassFail', 'disable', this)
* 
* @param	fieldsetId - Fieldset we are working in
* @param	cssIdentifier - A valid CSS identifier for the items to enable/disable 
* @param	toggleSwitch - Either 'enable' or 'disable'
* @param	exception - An element to exempt from disable
*/
function toggleFieldsetItemEnable(fieldsetId, cssIdentifier, toggleSwitch, exception){
	cssIdentifier = (typeof cssIdentifier == "undefined")?'select.cf2customFieldSelectPassFail':cssIdentifier;
	toggleSwitch = (typeof toggleSwitch == "undefined")?'disable':toggleSwitch;
	var nodes = $(fieldsetId).select(cssIdentifier);
	nodes.each(function(node){
		if( ((typeof exception != "undefined") && (node == exception)) || (toggleSwitch == 'enable')){
			node.enable();
		}else{
			node.disable();
		}
	});
}

/**
* Simple sleep function
*
* Use to create a pause in javascript execution
* 
* @param	integer	Time in milliseconds
*/
sleep = function (delay){
	var start = new Date().getTime();
	while (new Date().getTime() < start + delay);
}


/**
* Class for detecting browsers
*
* Browser name: 	BrowserDetect.browser
* Browser version: 	BrowserDetect.version
* OS name: 			BrowserDetect.OS
*/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();



ajaxCreateWait = function(){
    var w = 100;
    
    var xWaitingDivx = document.createElement('div');
    xWaitingDivx.setAttribute('id', 'xWaitingDivx');
    xWaitingDivx.setStyle({
        backgroundColor: '#CCCCCC',
        height: '100%',
        margin: 'auto',
        opacity: '0.6',
        filter: 'alpha(opacity=60)',
        position: 'fixed',
        textAlign: 'center',
        top: 0,
        width: '100%',
        zIndex: 100000
    });
    
    var xWaitingInnerDivx = document.createElement('div');
    xWaitingInnerDivx.setAttribute('id', 'xWaitingInnerDivx');
    xWaitingInnerDivx.setStyle({
        backgroundColor: '#FFFFFF',
        border: '1px solid black',
        background: 'url(/pros_images_backend/bg_fade.jpg) repeat-x scroll left top',
        margin: 'auto',
        padding: '10px',
        position: 'absolute',
        textAlign: 'center',
        top: '50%',
        width: w+'px',
        zIndex: 100001
    });
    
    var xLoadingx = document.createElement('h1');
    xLoadingx.innerHTML = 'LOADING';
    
    var xWaitingImgx = document.createElement('img');
    xWaitingImgx.setAttribute('id', 'xWaitingImgx');
    xWaitingImgx.setAttribute('src', '/pros_images/indicator-large.gif');
    xWaitingImgx.setStyle({
        margin: 'auto',
        textAlign: 'center',
        display: 'block',
        zIndex: 100002
    });
    
    xWaitingInnerDivx.appendChild(xLoadingx);
    xWaitingInnerDivx.appendChild(xWaitingImgx);
    document.body.appendChild(xWaitingDivx);
    document.body.appendChild(xWaitingInnerDivx);
    
    function resize(){
        var winW = window.innerWidth;
        $("xWaitingInnerDivx").style.left = (winW - w)/2 + "px";
    }
    resize();
    window.onresize = resize;
}
ajaxRemoveWait = function(){
    $('xWaitingDivx').remove();
    $('xWaitingInnerDivx').remove();
    window.onresize = '';
}



