/*********************************************************************************/
/*	This file is part of "Affilate Lead Site".                                   */
/*                                                                               */
/*	"Affilate Lead Site" 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 2 of the License, or            */
/*	(at your option) any later version.                                          */
/*                                                                               */
/*	"Affilate Lead Site" 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 "Affilate Lead Site" (see COPYING.txt); if not, write to the      */
/*  Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,                 */
/*  Boston, MA  02110-1301  USA                                                  */
/*********************************************************************************/

var mousex = 0;
var mousey = 0;
var algor = 0;

function initMouse()
{
   //document.onmousemove = updateMouse; // update(event) implied on NS, update(null) implied on IE
   //updateMouse();
   document.onmousemove = follow;
}

function getMouseXY(e) // works on IE6,FF,Moz,Opera7
{ 
  if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)

  if (e)
  { 
    if (e.pageX || e.pageY)
    { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
      mousex = e.pageX;
      mousey = e.pageY;
      algor = '[e.pageX]';
      if (e.clientX || e.clientY) algor += ' [e.clientX] '
    }
    else if (e.clientX || e.clientY)
    { // works on IE6,FF,Moz,Opera7
      mousex = e.clientX + document.body.scrollLeft;
      mousey = e.clientY + document.body.scrollTop;
      algor = '[e.clientX]';
      if (e.pageX || e.pageY) algor += ' [e.pageX] '
    }  
  }
}

function updateMouse(e)
{
  getMouseXY(e); // NS is passing (event), while IE is passing (null)
}



// xMoveTo r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xMoveTo(e,x,y)
{
  xLeft(e,x);
  xTop(e,y);
}

// xLeft r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xLeft(e, iX)
{
  if(!(e=xGetElementById(e))) return 0;
  var css=xDef(e.style);
  if (css && xStr(e.style.left)) {
    if(xNum(iX)) e.style.left=iX+'px';
    else {
      iX=parseInt(e.style.left,10);
      if(isNaN(iX)) iX=xGetComputedStyle(e,'left',1);
      if(isNaN(iX)) iX=0;
    }
  }
  else if(css && xDef(e.style.pixelLeft)) {
    if(xNum(iX)) e.style.pixelLeft=iX;
    else iX=e.style.pixelLeft;
  }
  return iX;
}

// xTop r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xTop(e, iY)
{
  if(!(e=xGetElementById(e))) return 0;
  var css=xDef(e.style);
  if(css && xStr(e.style.top)) {
    if(xNum(iY)) e.style.top=iY+'px';
    else {
      iY=parseInt(e.style.top, 10);
      if(isNaN(iY)) iY=xGetComputedStyle(e,'top',1);
      if(isNaN(iY)) iY=0;
    }
  }
  else if(css && xDef(e.style.pixelTop)) {
    if(xNum(iY)) e.style.pixelTop=iY;
    else iY=e.style.pixelTop;
  }
  return iY;
}

// xDef r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xDef()
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
  return true;
}

// xGetElementById r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xGetElementById(e)
{
  if(typeof(e)=='string') {
    if(document.getElementById) e=document.getElementById(e);
    else if(document.all) e=document.all[e];
    else e=null;
  }
  return e;
}

// xStr r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xStr(s)
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])!='string') return false;}
  return true;
}

// xNum r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xNum()
{
  for(var i=0; i<arguments.length; ++i){if(isNaN(arguments[i]) || typeof(arguments[i])!='number') return false;}
  return true;
}

// xGetComputedStyle r8, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xGetComputedStyle(oEle, sProp, bInt)
{
  var s, p = 'undefined';
  var dv = document.defaultView;
  if(dv && dv.getComputedStyle){
    s = dv.getComputedStyle(oEle,'');
    if (s) p = s.getPropertyValue(sProp);
  }
  else if(oEle.currentStyle) {
    // convert css property name to object property name for IE
    var i, c, a = sProp.split('-');
    sProp = a[0];
    for (i=1; i<a.length; ++i) {
      c = a[i].charAt(0);
      sProp += a[i].replace(c, c.toUpperCase());
    }
    p = oEle.currentStyle[sProp];
  }
  else return null;
  return bInt ? (parseInt(p, 10) || 0) : p;
}


// xPageY r4, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xPageY(e)
{
  var y = 0;
  e = xGetElementById(e);
  while (e) {
    if (xDef(e.offsetTop)) y += e.offsetTop;
    e = xDef(e.offsetParent) ? e.offsetParent : null;
  }
  return y;
}

// xPageX r2, Copyright 2001-2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xPageX(e)
{
  var x = 0;
  e = xGetElementById(e);
  while (e) {
    if (xDef(e.offsetLeft)) x += e.offsetLeft;
    e = xDef(e.offsetParent) ? e.offsetParent : null;
  }
  return x;
}

function showHelp(val, helpLinkId)
{
    document.getElementById("helpDiv").style.visibility = "visible";
    document.getElementById("helpText").innerHTML = eval(val+"Message");
    
    var t = getHelpLinkTop(document.getElementById(helpLinkId));
	var l = getHelpLinkLeft(document.getElementById(helpLinkId));
	
    xMoveTo("helpDiv",l,t);
    try
    {
        document.getElementById("helpClose").focus();
    }
    catch(err)
    {
        //nothing
    }
}

function hideHelp()
{
    document.getElementById("helpText").innerHTML = "";
    document.getElementById("helpDiv").style.visibility = "hidden";
    focusOnFirstControl();
}

/* Offset position from top of the screen */
function getHelpLinkTop(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function getHelpLinkLeft(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}
/* ------ End of Offset function ------- */


function convertToSlash(sDate)
{
    //User can enter mm/dd/yyyy or mm-dd-yyyy.  We convert to mm/dd/yyyy in all cases.   
    if(!isNullOrEmpty(sDate))
    { 
        sDate = sDate.replace(/-/g, '/');
    }
    sDate = convertYear(sDate);
    return sDate;  
}

//Returns if a string has any non numbers.
function IsNumeric(text){
   var validChars = "0123456789";
   var isNumber = true;
   var character = null;
   for (var i = 0; i < text.length && isNumber == true; i++){ 
      character = text.charAt(i); 
      if (validChars.indexOf(character) == -1){
         isNumber = false;
      }
   }
   return isNumber;   
}

function convertYear(sDate)
{
    try
    {
        var dateparse;
               
        if (sDate.indexOf("/") >= 0)
			dateparse = sDate.split("/");
		else if (sDate.indexOf("-") >= 0)
		    dateparse = sDate.split("-");
		else
			throw new Error("Invalid input string");
			
		if (dateparse.length < 2 || dateparse.length > 3) //make sure this is a valid date, even tho there probably is a regular expression validator
		    throw new Error("Invalid input string");
		    
		//make sure we have a 4 digit year
        dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
		if (dateparse.length == 2)
		{    
		    sDate = dateparse[0] + "/" + dateparse[1];	
        }	
        else
        {
            sDate = dateparse[0] + "/" + dateparse[1] + "/" + dateparse[2];	
        }
	}	
	catch (exception)
    {
        return sDate;
    }
    return sDate;     		   
}

function isDate(sDate)
{ 
    try
    {
        var dateparse;
               
        if (sDate.indexOf("/") >= 0)
			dateparse = sDate.split("/");
		else if (sDate.indexOf("-") >= 0)
		    dateparse = sDate.split("-");
		else
			throw new Error("Invalid input string");
			
		if (dateparse.length < 2 || dateparse.length > 3) //make sure this is a valid date, even tho there probably is a regular expression validator
			throw new Error("Invalid input string");

        //make sure we have a 4 digit year
        dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
        
        if (dateparse.length == 2)
			dateparse = [dateparse[0], "01", dateparse[1]];
		
		var year = dateparse[dateparse.length-1];
		var dayofmonth = [31,28,31,30,31,30,31,31,30,31,30,31];

		// check to see if this is a leap year and change days in Feb accordingly
		dayofmonth[1] = (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );

		if (dateparse[1] > 0 && dateparse[1] <= dayofmonth[dateparse[0]-1])
		{
		    return true;
		}
		else
		{
		    return false;
		}
		    
	}  
	catch (exception)
    {
        return false;
    }
}

//returns a 4 digit year.  If a 2 digit year is supplied, the century will be added.
function getCentury(inStr)
{
	if (inStr.length == 2)
	{
		var tmpDate = new Date();

		var century = parseInt(tmpDate.getFullYear().toString().substring(0,2), 10);
		var year = parseInt(tmpDate.getFullYear().toString().substring(2), 10);
		
		if (inStr <= (year + 10)) //add 10 to the current year to handle dates up to 10 year in the future
			return century + inStr;
		else
			return (century - 1) + inStr;
    }
    else
		return inStr;
}

//return true if the date is within the time span specified
//false if there is an exception or not within the time span.
// spanStart and spanEnd expect a negative value for the past, positive value for the future specified in days
// ex. isDateInRange("11/1/2005", -365, 0) would be true if the date specified is within 12 months of the current date.
function isDateInRange(tmpDate, spanStart, spanEnd)
{
    try
    {
        var testDate = new Date();
        var dateparse;
        
        if (tmpDate.indexOf("/") >= 0)
			dateparse = tmpDate.split("/");
		else if (tmpDate.indexOf("-") >= 0) 
			dateparse = tmpDate.split("-");
		else
			return false;

		if (dateparse.length < 2 || dateparse.length > 3) //make sure this is a valid date, even tho there probably is a regular expression validator
			return false;

        if (dateparse.length == 2)
        {
			dateparse = [dateparse[0], "01", dateparse[1]];              
			//make sure we have a 4 digit year
            dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
		}
		
		if (dateparse.length == 3)
        {
			dateparse = [dateparse[0], dateparse[1], dateparse[2]];              
			//make sure we have a 4 digit year
            dateparse[dateparse.length-1] = getCentury(dateparse[dateparse.length-1]);
		}	

        // create a properly formatted date 
        testDate = new Date();
        testDate.setFullYear(dateparse[2], dateparse[0] - 1, dateparse[1]); // setFullYear(year, month, day);
        //alert("testDate: " + testDate.toString());
        var startDate = new Date(); 
        var endDate = new Date();
        
        startDate.setHours(0,0,0,0);
        endDate.setHours(23, 59, 59, 999);
        
        //check our timespan values, make sure the past date is the older date
        if (spanEnd < spanStart)
        {
			startDate.setTime(startDate.getTime() + (86400000 * spanEnd)); //number of milliseconds in a day * the number of days)
			endDate.setTime(endDate.getTime() + (86400000 * spanStart));
        }
        else
        {
			startDate.setTime(startDate.getTime() + (86400000 * spanStart)); //number of milliseconds in a day * the number of days)
			endDate.setTime(endDate.getTime() + (86400000 * spanEnd));
        }
		
        // check the date range with current date and the past date or span
        if (testDate >= startDate && testDate <= endDate)
            return true;
        else
            return false;
    }
    catch (exception)
    {
        return false;
    }
}

//trims the white space from the beginning and end of the input string.
function trim(inStr)
{
	var start;
	var end;
	for (start = 0; start < inStr.length; start++)
	{
		if (inStr[start] != ' ')
		{
			break;
		}
	}
	for (end = inStr.length; end >= 0; end--)
	{
		if (inStr[end] != ' ')
		{
			break;
		}
	}
	
	if (start == end)
		return '';
	else
		return inStr.substring(start, end);
		
}

function isNullOrEmpty(obj)
{
    if(obj == "" || obj == null)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function doNothing()
{
    //I implemented this because I was having trouble with javascript:void() on some of the help hyperlinks
    return;
}

//This will display the error messages on the page if server validations fail
function showError(id){
	if (document.getElementById(id) != undefined)
	{	
		//check to see if it is only hidden
		if(document.getElementById(id).style.visibility == "hidden")
		{
		    document.getElementById(id).style.visibility == "visible"
		}
		else
		{
		document.getElementById(id).style.display = "block";
		}
	}
	else
	{
		if (document.getElementById("genericServerError") != undefined)
		{
			document.getElementById("genericServerError").style.display = "block";	
		}
	}
}

//Will set the focus to the first control in the page that
//is not disabled or hidden
function focusOnFirstControl()
{		
    var bFound = false;

    // for each form
    for (f=0; f < document.forms.length; f++)
    {
        // for each element in each form
        for(i=0; i < document.forms[f].length; i++)
        {
            // if it's not a hidden element
            if (document.forms[f][i].type != "hidden")
            {
                // and it's not disabled
                if (document.forms[f][i].disabled != true)
                {
                    // set the focus to it
                    document.forms[f][i].focus();
                    var bFound = true;
                }
            }
            // if found in this element, stop looking
            if (bFound == true)
                break;
        }
        // if found in this form, stop looking
        if (bFound == true)
            break;
    }		
}

function setfocus(field_id) 
{
        try
        {
            document.forms[0][field_id].focus();
        }
        catch (exception)
        {
            
        }
}

// List of node types that have a "disabled" attribute.  
// Add elements here that have a "disabled" attribute associated with them
// You will need to verify that a control can really be disabled by using a 
// W3C DOM standards-compliant browser (meaning not Internet Explorer).
var disableableNodes = {
	input: 1,
	a: 1,
	select: 1,
	table: 1
};

// List of node types that don't have a "disabled" attribute, 
// we will style them to look like they are disabled.
var otherNodes = {
	label: 1,
	td: 1,
	th: 1,
	span: 1,
	div: 1
};

//disables an element and all children
//pass in "true" or "false" (yes you need quotes) for state.
//"true" means disable, "false" will re-enable.
function disableControl(control, state) {       // control is a Node 
    try
    {
        if (control.nodeType == 1)                  // Node.ELEMENT_NODE
        {
            if (control.nodeName.toLowerCase() in disableableNodes)
            {
                control.disabled = state;
            }
            else if (control.nodeName.toLowerCase() in otherNodes)
            {
                if (state)
                    control.className = "label-off";
                else
                    control.className = "label-on";
            }
        }
    
        var childs = control.childNodes;          // Now get all children of n
        for(var i=0; i < childs.length; i++) {    // Loop through the children
            disableControl(childs[i], state);	  // Do a recursive call to find all child controls
        }
     }                             
     catch (exception)
     {
     }   
}

//Limits the length of a text area.
//field - the text area you want to limit the length of
//countfield - characters remaining value field
//maxlimit - max length of the text area
function textCounter(field, countfield, maxlimit)
{
	if (field.value.length > maxlimit)
		field.value = field.value.substring(0, maxlimit);					
	else if (countfield != null)
		countfield.innerHTML = maxlimit - field.value.length;
}

//Sets a default string if the field is left blank.  Updates the counter field.
function setText(defaultString, field, countfield, maxlimit)
{   
    if (field.value == '')
	    field.value = defaultString;					
	textCounter(field,countfield,maxlimit);
}

//Clears the default string from the comment area when the user selects 
function clearText(defaultString, field, countfield, maxlimit)
{
    if (field.value == defaultString) 
	    field.value = '';
	textCounter(field,countfield,maxlimit);    
}


//removes all non-numeric characters from a string.  Decimals will be kept.
function removeNonNumerics(inStr)
{
	var validChars = "0123456789.";
	var outStr = "";
	for(var i = 0; i < inStr.length; i++){
		if(validChars.indexOf(inStr.charAt(i)) != -1)
			outStr += inStr.charAt(i);
	}
	return outStr;
}


function removeCents(val){
    
    var input = new String(val);
    
    var decimalLocation = input.indexOf(".");
    
    if(decimalLocation > 0){
        return removeNonNumerics(input.substr(0,decimalLocation));
    }
    else{
        return removeNonNumerics(input);
    }
}

// Simple follow the mouse script
function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY) return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

function follow(evt)
{
    if (document.getElementById)
    {
        mousex = (parseInt(mouseX(evt), 10));
        mousey = (parseInt(mouseY(evt), 10));
        //window.status = "x= " + mouseX(evt) + " y= " + mouseY(evt);
    }
}
//Write to a hidden field if JavaScript is enabled.  If it isn't enabled there won't be a value in the field.
function testJavaScriptEnabled(){
    var javaScriptTestElement = document.getElementById("JavaScriptTestID");
    if (javaScriptTestElement != undefined){
        javaScriptTestElement.value = "Enabled";
    }
}

// Return the control that generated the event
function getEventTarget(evt){ 
    evt = (evt) ? evt : (window.event) ? window.event : ""; 
    var elt; 
    if (evt.srcElement){ 
        elt = evt.srcElement; 
    }
    else if (evt.target){ 
        elt = evt.target; 
    } 
    return elt;
}
//Modified .Net Supplied function.  This function will cause a press of the enter key to fire the default button unless the 
//enter button was pressed for a submit or image button or for a help popup.  This allows the back button and help links to still function normally.
function fireDefaultButton(event, target){
    var evtTarget = getEventTarget(event);
    var fireDefault = false;
    if (event.keyCode == 13){
        if (evtTarget){
            var tagName = evtTarget.tagName.toLowerCase();
            if (tagName == "textarea"){
                fireDefault = false;
            }
            else if (tagName == "input"){                            
                if (evtTarget.type.toLowerCase() == "image" || evtTarget.type.toLowerCase() == "submit"){
                    fireDefault = false;
                }
                else {
                    fireDefault = true;
                }
            }
            else if (evtTarget.parentNode.className == "helpLinks"){                
                fireDefault = false;                
            }
            else if (tagName == "a"){
                fireDefault = false;
            }
            else {
                fireDefault = true;
            }
        }
    }
    var returnValue = true;
    if (fireDefault){
        var defaultButton = document.getElementById(target);
        if (defaultButton && typeof(defaultButton.click) != "undefined"){
            defaultButton.click();
        //if (defaultButton && typeof(defaultButton.submit) != "undefined"){
        //    defaultButton.submit();
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
            returnValue = false;
        }
    }
    return returnValue;
}

//Will set the focus to the first control in the page that
//is not disabled or hidden
function focusOnFirstControl()
{		
    var bFound = false;
    
    // for each form
    for (f=0; f < document.forms.length; f++)
    {   
        if (document.forms[f].length == 0){
            var continueButtonElement = document.getElementById('ContinueBtn');
            if (continueButtonElement != undefined){
                continueButtonElement.focus();
                bFound == true;
                break;
            }
        }     
        // for each element in each form
        for(i=0; i < document.forms[f].length; i++)
        {
            // if it's not a hidden element
            if (document.forms[f][i].type != "hidden")
            {
                // and it's not disabled
                if (document.forms[f][i].disabled != true)
                {
                    // set the focus to it
                    document.forms[f][i].focus();
                    var bFound = true;
                }
            }
            // if found in this element, stop looking
            if (bFound == true)
                break;
        }
        // if found in this form, stop looking
        if (bFound == true)
            break;
    }		
}