
var CONTROl_TYPE_OPPORTUNITY = 319;
var CONTROl_TYPE_LEAD = 320;
var CONTROl_TYPE_ACCOUNT_PLAN = 8641;
var CONTROl_TYPE_SERVICE_CALL = 8642;
var CONTROl_TYPE_PROJECT = 8643;

var IE_WINDOW_HEADER = 31;
var BUTTON_PREFIX = "_tbl";

function IsArrayContain(arr, obj)
{
	var i;
	if (!arr)
		return false;
	if (!arr.length)
		return false;
	for(i = 0; i < arr.length; i++)
	{
		if (arr[i] == obj)
			return true;
	}
	return false;
}

function Array_RemoveElement(array, element)
{
	var i = 0;
	for (; i < array.length; i++)
	{
		if (array[i] == element)
			break;
	}
	if (i < array.length)
	{
		for (++i; i < array.length; i++)
		{
			array[i - 1] = array[i];
		}
		array.pop();
	}
}

function EncodeSemicolonSeparator(sValue)
{
	var sEncoded = String(sValue);
	var re = /\\/gm;
	var sEncoded = sEncoded.replace(re, "\\\\");
	re = /;/gm;
	sEncoded = sEncoded.replace(re, "\\,");
	re = /\r/gm;
	sEncoded = sEncoded.replace(re, "\\r");
	re = /\n/gm;
	sEncoded = sEncoded.replace(re, "\\n");
	re = /</gm;
	sEncoded = sEncoded.replace(re, "\<");
	re = />/gm;
	sEncoded = sEncoded.replace(re, "\>");
	return sEncoded;
}

function DecodeSemicolonSeparator(sValue)
{
    if (sValue==null){
    return "";
    }
    var sDecoded=String(sValue);
	var re = /\\,/gm;
	var sDecoded = sDecoded.replace(re, ";");
	re = /\\n/gm;
	sDecoded = sDecoded.replace(re, "\n");
	re = /\\>/gm;
	sDecoded = sDecoded.replace(re, ">");
	re = /\\</gm;
	sDecoded = sDecoded.replace(re, "<");
	re = /\\r/gm;
	sDecoded = sDecoded.replace(re, "\r");
	re = /\\\\/gm;
	sDecoded = sDecoded.replace(re, "\\");	
	return sDecoded;
}

function EncodeCommaSeparator(sValue)
{
	var sEncoded = String(sValue);
	var re = /\\/gm;
	var sEncoded = sEncoded.replace(re, "\\\\");
	re = /,/gm;
	sEncoded = sEncoded.replace(re, "\\;");
	re = /\r/gm;
	sEncoded = sEncoded.replace(re, "\\r");
	re = /\n/gm;
	sEncoded = sEncoded.replace(re, "\\n");
	re = /</gm;
	sEncoded = sEncoded.replace(re, "\<");
	re = />/gm;
	sEncoded = sEncoded.replace(re, "\>");
	return sEncoded;
}

function DecodeCommaSeparator(sValue)
{
    if (sValue==null){
    return "";
    }
    var sDecoded=String(sValue);
	var re = /\\;/gm;
	var sDecoded = sDecoded.replace(re, ",");
	re = /\\n/gm;
	sDecoded = sDecoded.replace(re, "\n");
	re = /\\>/gm;
	sDecoded = sDecoded.replace(re, ">");
	re = /\\</gm;
	sDecoded = sDecoded.replace(re, "<");
	re = /\\r/gm;
	sDecoded = sDecoded.replace(re, "\r");
	re = /\\\\/gm;
	sDecoded = sDecoded.replace(re, "\\");	
	return sDecoded;
}

function EncodeHindusSeparator(sValue)
{

	var sEncoded = String(sValue);
	var re = /\\/gm;
	var sEncoded = sEncoded.replace(re, "\\\\");
	re = /\|/gm;
	sEncoded = sEncoded.replace(re, "\\1");
	re = /\[/gm;
	sEncoded = sEncoded.replace(re, "\\3");
	re = /\]/gm;
	sEncoded = sEncoded.replace(re, "\\4");
	re = /~/gm;
	sEncoded = sEncoded.replace(re, "\\2");
	return sEncoded;
}

function DecodeHindusSeparator(sValue)
{
   if (sValue==null){
    return "";
    }
    var sDecoded=String(sValue);
	var re = /\\1/gm;
	var sDecoded = sDecoded.replace(re, "|");
	re = /\\3/gm;
	sDecoded = sDecoded.replace(re, "[");
	re = /\\4/gm;
	sDecoded = sDecoded.replace(re, "]");
	re = /\\2/gm;
	sDecoded = sDecoded.replace(re, "~");
	re = /\\\\/gm;
	sDecoded = sDecoded.replace(re, "\\");	
	return sDecoded;
}

function createRequestObject() 
{ 
    var request   = new Object();       // Creates a new request object. 
    var nameVal   = "";                 // Holds array for a single name-value pair. 
    var inString  = location.search;    // Strips query string from URL. 
    var separator = ",";                 // Character used to separate multiple values. 

	  // If URL contains a query string, grabs it. 
    if (inString.charAt(0) == "?") 
    { 
        // Removes "?" character from query string. 
        inString = inString.substring(1, inString.length); 
        // Separates query string into name-value pairs. 
        keypairs = inString.split("&"); 
        // Loops through name-value pairs. 
        for (var i=0; i < keypairs.length; i++) 
        { 
            // Splits name-value into array (nameVal[0]=name, nameVal[1]=value). 
            nameVal = keypairs[i].split("="); 

            // Checks to see if name already exists in request object 
            // (since select lists may contain multiple values). 
            if (request[nameVal[0]]) 
            { 
          		request[nameVal[0]] += separator + nameVal[1]; 
            } 
            else 
            { 
            	request[nameVal[0]] = nameVal[1]; 
            } 
        } 
    } 
    return request; 
} 


function validateDate(sDate)
{
	if (sDate == "")
		return true;
	sDate = Trim(sDate);	
    var dt;
    var isValid = 0;
    var sSep = ['/','\\','.','-'];
    var validFormat = false;
    
    for(var i = 0; i < sSep.length; i++)
    {
        a_dt = sDate.split(sSep[i]);
        if (a_dt.length == 3 && (a_dt[2].length == 2 || a_dt[2].length == 4))
        {
            validFormat = true;
            break;
        }
    }
    
    if (validFormat)
    {
		var mm = a_dt[1];
		var dd = a_dt[0];			
		
		if (typeof(global_culture) != "undefined")
		{
		    if(global_culture.toLowerCase() == "en-us")
		    {
			    mm = a_dt[0];
			    dd = a_dt[1];
		    }
		}
		
        var yyyy = parseInt(a_dt[2]);
        if (!isNaN(mm) && !isNaN(dd) && !isNaN(yyyy))
        {
            if(!yyyy) yyyy = 2000;            
			var dt = new Date(yyyy, mm-1, dd);
			
            if(!isNaN(dt))
            {
                if (mm==(dt.getMonth()+1) && dd==dt.getDate() && yyyy==dt.getYear())
					return true;
            }
        }
    }
	return false;
}

function validateTime(sTime)
{
	sTime = Trim(sTime);
	var a_t = sTime.split(':');
	var hh = a_t[0];
	var mm = a_t[1];
	if (!isNaN(hh) && !isNaN(mm))
	{
		if (hh >= 0 && hh <= 23 && mm >= 0 && mm <= 59)
			return true;
	}
	
	return false;
}

function validateDateTime(sDateTime)
{
	sDateTime = Trim(sDateTime);
	var iSpaceIndex = sDateTime.indexOf(" ");
	var sDate;
	var sTime;
	if (iSpaceIndex > -1)
	{
		sDate = sDateTime.substr(0, iSpaceIndex);
		if (!validateDate(sDate))
			return false;
		sTime = sDateTime.substr(iSpaceIndex + 1);
		return validateTime(sTime);
	}
	else
	{
		return validateDate(sDateTime)
	}
}

function validateControls(aControls)
// 0 - Control
// 1 - type
// 2 - required
// 3 - wrong msg
// 4 - required msq
{
	if (!aControls)
		return true;
	var i;
	var j;
	for(i = 0; i < aControls.length; i++)
	{
		if (aControls[i])
		{
			if (aControls[i][2])
			{
				if (aControls[i][0].value == "")
				{
					alert(aControls[i][4]);
					try
					{
						aControls[i][0].focus();
					}
					catch(err)
					{}
					return false;
				}
			}
			var bWrong = false;
			switch(aControls[i][1])
			{
				case "datetime":
					bWrong = !validateDateTime(aControls[i][0].value);
					break;
				case "float":
					bWrong = !validateFloat(aControls[i][0].value);
					break;
			}
			if (bWrong)
			{
				alert(aControls[i][3]);
				try
				{
					aControls[i][0].focus();
				}
				catch(err)
				{}
				return false;			
			}
		}
	}
	return true;
} 

function addValidator(aControls, ctl, sType, bRequired, sWrongMsg, sRequiredMsq)
{
	if (!aControls.length)
		aControls = new Array();
	
	var aControl = new Array();
	aControl[0] = ctl;
	aControl[1] = sType;
	aControl[2] = bRequired;
	aControl[3] = sWrongMsg;
	aControl[4] = sRequiredMsq;
	aControls[aControls.length] = aControl;
	return aControls;
}

function LTrim(str){
   //var whitespace = new String(" \t\n\r");
   var whitespace = new String(" ");
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      var j=0, i = s.length;

      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;

      s = s.substring(j, i);
   }
   return s;
}

function RTrim(str){
   var whitespace = new String(" ");

   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;

      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }

   return s;
}

function Trim(str){
   return RTrim(LTrim(str));
}

function HTMLDecode(sValue)
{
    var sDecoded=String(sValue);
    
	var re = /&lt;/gm;
	var sDecoded = sDecoded.replace(re, "<");
	re = /&gt;/gm;
	sDecoded = sDecoded.replace(re, ">");
	re = /&amp;/gm;
	sDecoded = sDecoded.replace(re, "&");
	re = /&quot;/gm;
	sDecoded = sDecoded.replace(re, "\"");
	re = /&nbsp;/gm;
	sDecoded = sDecoded.replace(re, " ");
	
	return sDecoded;
}

function HTMLEncode_2(sValue)
{
    var sDecoded=String(sValue);
    
	var re = /</g;
	var sDecoded = sDecoded.replace(re, "&lt;");
	re = />/g;
	sDecoded = sDecoded.replace(re, "&gt;");
	re = /&/g;
	sDecoded = sDecoded.replace(re, "&amp;");
	re = /\"/g;
	sDecoded = sDecoded.replace(re, "&quot;");
	return sDecoded;
}


function DimScreen()
{
	if(document.all.DimScreenDiv)
	{
		document.all.DimScreenDiv.style.display = "inline";
	}
}

function UnDimScreen()
{
	if(document.getElementById("DimScreenDiv"))
		document.getElementById("DimScreenDiv").style.display = "none";
}
		
function validateInt(sValue)
{
	var i = new Number(sValue);
	if (isNaN(i))
		return false;
	var s = String(i);
	if(s.indexOf(".")!=-1)
		return false;
	return true;
}

function validateIntRange(sValue, iMin, iMax)
{
	if(validateInt(sValue))
	{
		var i = parseInt(sValue);
		return((i>=iMin)&&(i<=iMax));
	}
	else
		return false;
}

function validateFloat(sValue)
{
	var result = !isNaN(parseFloat(sValue));
	if(!result)
		return false;

	if(typeof(sValue)=="string")
	{
		var i = new Number(sValue);
		if (isNaN(i))
			return false;
	}
		
	return true;
}

function validaeteFloatRange(sValue, fMin, fMax)
{
	if(validateFloat(sValue))
	{
		var f = parseFloat(sValue);
		return((f>=fMin)&&(f<=fMax));
	}
	else
		return false;
}

function validateFloatPrecision(sValue, iPrecision)
{
	if(isNaN(iPrecision))
		iPrecision = 0;
		
	if(validateFloat(sValue) && ((iPrecision>=0) && (iPrecision <=10)))
	{
		var s = String(sValue);
		var i;
		if(s.indexOf(".") != -1)
		{
			i = s.length - s.indexOf(".") - 1;
		}
		else
			i = 0;
		
		return i <= iPrecision;
	}
	else
		return false;
}

function EncodeURL(sString)
{
	var re = /&/g;    
	sString = sString.replace(re, "%26"); 
	
	re = /#/g;
	sString = sString.replace(re, "%23");
	
	return sString;
}

function ToTDContent(sString)
{
	if (sString.length > 0)
		return sString;
	else
		return "&nbsp;";
}


function GetElementPosition(p_element)	
{
	var iLeft = 0;
	var iTop = 0;
	var currentElement = p_element;
	
	while (currentElement.tagName != "BODY" && currentElement.tagName != "DIV")
	{	
		iLeft += currentElement.offsetLeft;
		iTop += currentElement.offsetTop;
		currentElement = currentElement.offsetParent;
	}
	return new Position(iLeft, iTop);
}

function Position (p_iX, p_iY)
{
	this.X = p_iX;
	this.Y = p_iY;
	
	function ToString()
	{
		return (this.X + ',' + this.Y);
	}
	this.ToString = ToString;
}
			
function GetFramePosition(p_wnd, p_top)
{
 
    var framePosition;
    var iLeft = 0;
    var iTop = 0;
    var j = 0;
    do
    {
        j++;
        var frm;
		for(i = 0; i < p_wnd.parent.document.all.length; i++)
		{
			if(p_wnd.parent.document.all[i].contentWindow)
			{
    			if (p_wnd.parent.document.all[i].contentWindow == p_wnd)
	    		{
		    	    frm = p_wnd.parent.document.all[i];
			        break;
			    }
			 }
		}
		framePosition = GetElementPosition(frm);

		iLeft += framePosition.X;
		iTop  += framePosition.Y;
		p_wnd = p_wnd.parent;
    }
    while(p_wnd != p_top && p_wnd.parent != p_wnd)
    
    return new Position(iLeft, iTop);
}						

function GetControlTypeName(p_iControlTypeID)
{
	switch(p_iControlTypeID)
	{
		case CONTROl_TYPE_OPPORTUNITY: 
			return "Opporunity";
		case CONTROl_TYPE_LEAD:
			return "Lead";
		case CONTROl_TYPE_ACCOUNT_PLAN:
			return "Account Plan";
		case CONTROl_TYPE_SERVICE_CALL: 
			return "Service Call";
		case CONTROl_TYPE_PROJECT:
			return "Project";
		default:
			return "";
	}
}

function RedirectToMyCustomer(p_wnd, p_sEntityID, p_sEntityTypeID)
{	
	var sLink = '../AccountManagement/Main.aspx';
	if (p_sEntityID != '' && p_sEntityTypeID != '')
	{
		sLink += '?EntityID=' + p_sEntityID;
		sLink += '&EntityTypeID=' + p_sEntityTypeID;
	}
	if (document.all.header_hdnMemberID)
		sLink += '&MemberID=' + document.all.header_hdnMemberID.value;
	p_wnd.location.href = sLink;
}

function AddQueryStringParameter(p_sHref, p_sName, p_sValue)
{				
	if (!(p_sHref.indexOf(p_sName + "=") > -1))
	{
		if (p_sHref.indexOf("?") > -1)
			p_sHref = p_sHref + "&";
		else
			p_sHref = p_sHref + "?";
				
		p_sHref = p_sHref + p_sName + "=" + p_sValue;
	}
	return p_sHref;					
}

function calculateDimensions(dimension, w, h, windowObject)
{
    if(!windowObject)
        windowObject = window;
    
    var iScreenWidth=screen.width;
    var iScreenHeight=screen.height;
    if (document.all)
    {
        var iDocumentWidth=windowObject.document.body.offsetWidth;
        var iDocumentHeight=windowObject.document.body.offsetHeight;
        var iDocumentTop=windowObject.screenTop;
        var iDocumentLeft=windowObject.screenLeft;
    }
    else
    {
        var iDocumentWidth=windowObject.outerWidth;
        var iDocumentHeight=windowObject.outerHeight;
        var iDocumentTop=windowObject.screenY;
        var iDocumentLeft=windowObject.screenX;
    }
   
    if(dimension=='left')
        return  iDocumentLeft+Math.round((iDocumentWidth-w)/2);
    else if(dimension=='top')
        return iDocumentTop+Math.round((iDocumentHeight-h)/2); 
}


function openWindow(url, name, w, h,attr)
{
    wleft=calculateDimensions('left',w,h);
    wtop=calculateDimensions('top',w,h);

    var win = window.open(url,
        name,
        'width=' + w + ', height=' + h + ', ' +
        'left=' + wleft + ', top=' + wtop + ', ' +
        attr);

    win.moveTo(wleft, wtop);
    win.focus();
    return win;
}

function openModalDialog(url, params, w, h, attr)
{
    wleft=calculateDimensions('left', w, h, top);
    wtop=calculateDimensions('top', w, h, top);

    var resObj = window.showModalDialog(url,
        params,
        'dialogWidth=' + w + 'px; dialogHeight=' + h + 'px; ' +
        'dialogLeft=' + wleft + 'px; dialogTop=' + wtop + 'px; ' +
        attr);

    return resObj;
}

function openWindowFromHref(url, name, w, h)
{
    openCenteredWindowWithScrollers(url, name, w, h);    
}

function openCenteredWindowWithScrollers(url, name, w, h)
{
    return openWindow(url, name, w, h, 'location=no, menubar=no,status=no, toolbar=no, scrollbars=yes, resizable=yes');
} 

function openCenteredWindowWOScrollers(url, name, w, h)
{
    openWindow(url, name, w, h, 'location=no, menubar=no,status=no, toolbar=no, scrollbars=no, resizable=no');
}

function openCenteredModalDialogWOScrollers(url, params, w, h)
{
    return openModalDialog(url, params, w, h, 'center=no; help=no; resizable=no; scroll=no; status=no;');
}

function OpenResults(p_sTableID, p_iRecordID, p_iDataDirection)
{
    var sURL = 'ViewForm.aspx?TableID=' + p_sTableID + '&RecordID=' + p_iRecordID + '&DataDirection=' + p_iDataDirection;
    openCenteredWindowWOScrollers(sURL, p_sTableID, 800, 600);
}

function OpenNewSearch(p_sTableID, p_iDataDirection, p_iCustomerID)
{    
    if(p_iCustomerID)
        var sURL = 'ViewForm.aspx?TableID=' + p_sTableID + '&DataDirection=' + p_iDataDirection + '&CustomerID=' + p_iCustomerID;
    else
        var sURL = 'ViewForm.aspx?TableID=' + p_sTableID + '&DataDirection=' + p_iDataDirection;
    openCenteredWindowWOScrollers(sURL, p_sTableID, 800, 600);
}

function OpenEntityForm(p_sDir, p_sType, p_sTableID, p_iKey)
{
    var sURL = "";
    if(p_sType == "Edit")
    {
        sURL += 'ViewForm.aspx?TableID=' + p_sTableID;
        sURL += (p_sDir == "Input") ? '&FK_ID=' + p_iKey : '&RecordID=' + p_iKey;    
    }
    else if(p_sType == "Grid")
        sURL = 'ViewGrid.aspx?TableID=' + p_sTableID + '&FK_ID=' + p_iKey + '&Direction=' + p_sDir;
    else
        return;        
    
    openCenteredWindowWOScrollers(sURL, p_sTableID, 800, 600);
}

function OpenContactForm(p_iContactID, p_AccountType)
{
    var sURL = 'ContactEdit.aspx?ContactID=' + p_iContactID + '&AccType=' + p_AccountType;
    openCenteredWindowWithScrollers(sURL, '', 800, 600);
}

function OpenDepartmentForm(p_iDepartmentID)
{
    var sURL = 'DepartmentEdit.aspx?DepartmentID=' + p_iDepartmentID;
    openCenteredWindowWithScrollers(sURL, '', 800, 600);
}

function OpenDesigner(p_sType, p_sTableID, p_iEntityTypeID)
{
    //debugger;
    var sURL = "";
    if(p_sType == "Edit")
        sURL = 'FormDesigner/ViewDesigner.aspx?GeoID=0&FormID=' + p_sTableID + '&EntityID=' + p_iEntityTypeID;
    else if(p_sType == "Grid")
        sURL = 'GridDesigner/WizardGridDesigner.aspx?GeoID=0&TableID=' + p_sTableID + '&ObjectDescriptionID=' + p_iEntityTypeID;
    else
        return;
    	
	var sFeatures = 'status=no,toolbar=no,menubar=no,location=no,resizable=yes';
				
	OpenResizedWindow(sURL, 'Design', 1000, 700, 0, 100, sFeatures);	
}

function OpenResizedWindow(p_sURL, p_sWindowName, p_iWidth, p_iHeight, p_iTop, p_iLeft, p_sAdditionalParams, p_bResizeWindowOnLargeResolution)
{	
	if (p_bResizeWindowOnLargeResolution == null)
		p_bResizeWindowOnLargeResolution = true;
		
	if (p_iHeight == 0)
		p_iHeight = window.screen.availHeight;
		
	if ((p_iTop + p_iHeight) >= window.screen.availHeight)
	{
		p_iTop = 0;
		if (p_iHeight > window.screen.availHeight)
			p_iHeight = window.screen.availHeight;
	}
	else if (window.screen.availHeight > 870 && p_bResizeWindowOnLargeResolution)
		p_iHeight = 870;
		
	p_iHeight -= IE_WINDOW_HEADER;	
	
	if ((p_iLeft + p_iWidth) > window.screen.availWidth)
	{
		p_iLeft = 0;
		if (p_iWidth > window.screen.availWidth)
			p_iWidth = window.screen.availWidth;
	}
		
	var sParams = 'width=' + p_iWidth + ',height=' + p_iHeight + ',top=' + p_iTop + ',left=' + p_iLeft + ',' + p_sAdditionalParams;
		
	var wnd = window.open(p_sURL, p_sWindowName, sParams);
	wnd.focus();
	return wnd;	
}

function CorrectBlurButtonsText()
{
	if (document && document.all)
		for(var element in document.all)
		{
			var res = ' ';
			res = res + element;
			if (res.indexOf(BUTTON_PREFIX) > -1)
			{
				try
				{					
					res = res.substr(1, res.length);					
					var objTbl = eval ('document.all.' + res);										
					objTbl.rows[0].cells[1].children[0].innerHTML = objTbl.rows[0].cells[1].children[0].innerHTML;
				}
				catch(e)
				{}
			}					
		}
}

function EscapeDBWildcards(p_str)
{	
	if (p_str != null && 
		p_str != '' && 
		(p_str.indexOf('_') != -1 ||
		p_str.indexOf('%') != -1))
	{
		p_str = p_str.replace(/[_]/g, '[_]');
		p_str = p_str.replace(/[%]/g, '[%]');				
	}
	
	return p_str;
}

function UrlEncode(p_str)
{
	if (p_str == null)
		return "";
		
	var re = /&/g;
	p_str = p_str.replace(re, "%26");   
	
	re = /\r/g;
	p_str = p_str.replace(re, "%0D");   

	re = /\n/g;
	p_str = p_str.replace(re, "%0A");   
	
	re = /#/g;
	p_str = p_str.replace(re, "%23");   
	
	re = /\?/g;
	p_str = p_str.replace(re, "%3F"); 

	re = / /g;
	p_str = p_str.replace(re, "%20"); 
	return p_str;
}

function MVL_FieldWA()
{
	var FieldName; 
	var FriendlyName; 
	var Pattern;
	var Example; 
	var Required; 
	var ValidationFunction; 
	var ValidateOnSubmit;
	var LongMessage; 
	var boolShowErrorMsg;
}


function FormatCurrencyToInteger(value)
{
	var sValue = new String(value);
	var sFirst = "";
	if(sValue.length > 0 && sValue.substr(0, 1) == "-")
	{
		sFirst = sValue.substr(0, 1);
		sValue = sValue.substr(1, sValue.length - 1);
	}
	return sFirst + value.toString().replace(/\D/g, "");
}

function FormatIntegerToCurrency(value)
{
	var sValue = new String(value);
	var sFirst = "";
	if(sValue.length > 0 && sValue.substr(0, 1) == "-")
	{
		sFirst = sValue.substr(0, 1);
		sValue = sValue.substr(1, sValue.length - 1);
	}

	sValue = FormatCurrencyToInteger(sValue);

	// Remove leading zeros
	sValue = sValue.replace(/^[0]+/, "");
	
	if(value == "" || value == "0")
		return "0";
	
	var sResult = "";
	for(var i = sValue.length; i > 0; i -= 3)
	{
		var sTriad = sValue.substr(i - 3, (i-3)<0?i:3);
		sResult = sTriad + ((sResult.length != 0)?"," + sResult:"");
	}
	return sFirst + sResult;
//	return sResult;
}

function GetTopLevelOpener()
{
//debugger;
	var wnd = window;
	try
	{
		while(wnd != wnd.parent)
				wnd = wnd.parent;		
		while(wnd.opener != null)
		{
			wnd = wnd.opener;
			while(wnd != wnd.parent)
				wnd = wnd.parent;				
		}
		while(wnd != wnd.parent)
				wnd = wnd.parent;		
	}
	catch(err)
	{
		wnd = null;
	}
	return wnd;
}

function IsWindowLoaded(wnd)
{
	var bResult = false;
	try
	{
		if(wnd.document.all != null && wnd.document.readyState == 'complete') 
			bResult = true;
	}
	catch(err)
	{}
	return bResult;
}

function HiddenChildId() {
    this.control = null;
    this.update = update;
    
    function update(id) {
        debugger;        
        control.SetValue(id);
    }
}

var hiddenChildId = new HiddenChildId();

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function CheckMaxLength(Object, MaxLen)
{
  if(Object.value.length >= MaxLen)
  {     
    Object.value = Object.value.substring(0, MaxLen - 1);
  }
}

function formatCurrency (obj) {
	   anynum=obj;
	   divider =100;
	   workNum=Math.abs((Math.round(anynum*divider)/divider));
	   workStr=""+workNum
       if (workStr.indexOf(".")==-1){workStr+="."}
	   dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
	   pStr=workStr.substr(workStr.indexOf("."))
	   while (pStr.length-1< 2){pStr+="0"}
	   if(pStr =='.') pStr ='';
	   //--- Adds a comma in the thousands place.    
	   if (dNum>=1000) {
		  dLen=dStr.length
		  dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
	   }
	   //-- Adds a comma in the millions place.
	   if (dNum>=1000000) {
		  dLen=dStr.length
		  dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
	   }
	   retval = dStr + pStr
	   //-- Put numbers in parentheses if negative.
	   if (anynum<0) {retval="("+retval+")";}
 	   return retval;
 }
 
 function parseCurrency(sCurrency)
 {
    sCurrency = sCurrency + "";
    while (sCurrency.indexOf(",") != -1)
        sCurrency = sCurrency.replace(",", "");
    return parseFloat(sCurrency);
 }
 
 
function iframeSelfHeight(iTabNumber)
{
	setIframeHeight(iTabNumber, window.parent);
}

function setIframeHeight(iTabNumber, oMainWindow)
{
    if (oMainWindow == null) oMainWindow = window;
    
    // infragistics creates 2 iframe elements for each tab
    iFrameNumber = iTabNumber * 2;

    if (oMainWindow.frames.length > iFrameNumber)
    {
        var oIframe = oMainWindow.frames[iFrameNumber];
        oIframe.frameElement.style.height = "";

        var iIframeHeight = oIframe.document.body.scrollHeight;
        var iTabHeight = oIframe.frameElement.document.body.clientHeight
            - 27/*menu*/
            - 47/*navigation*/
            - 26 - 5/*tabs*/
            - 1;
            
        var iHeight = Math.max(iIframeHeight, iTabHeight);
        oIframe.frameElement.style.height = iHeight;
    }
}

function DownloadSample_KeyFacts(p_ProductTypeID)
{
    //window.open("DownloadDocument.aspx?ID=" + p_ProductTypeID, "DownloadDocument", "top=0, left=0, width=50, height=50, status=no, resizable=no, scrollbars=no, menubar=no, location=no");
    window.location.href = "DownloadDocument.aspx?ID=" + p_ProductTypeID;
}

function IsWideScreen()
{
    return screen.width >= 1024;
}

function OpenUWC(productID)
{
    var sURL = "UnderwritingCriteria.aspx" + (productID != 0 ? "?Product=" + productID : "");
    window.open(sURL, "UnderwritingCriteria", "width=800, height=600, status=no, menubar=no, location=no, resizable=yes, scroll:yes, scrollbars=yes");
}

function CheckParishValues() {
    
    if (typeof (aParishTexboxesForValidate) == 'undefined')
        return true;

    for (var iTextBox = 0; iTextBox < aParishTexboxesForValidate.length; iTextBox++) {
        if (document.getElementById(aParishTexboxesForValidate[iTextBox]).isInvalid)
            return false;
    }
    return true;
}


function lnkGetSample_Click(detailID)
{
    window.location.href = 'DownloadInsuranceInvoiceFile.ashx?Type=3&DetailID=' + detailID;
}

function ValidateBuildingNumber(p_errCtl, p_args)
{
    var oNames = ["Case.Building Number", "Case.Building Name", "Case.Paon"];
    var oController = GetSmartClientController();
    p_args.IsValid = false;
    for (var i = 0; i < oNames.length; i++)
    {
        var oSmart = oController.GetControlByAlias(oNames[i]);
        if (oSmart != null)
        {
            if (oSmart.GetValue() != "")
            {
                p_args.IsValid = true;
                break;
            }
        }
    }
}

function ValidateSingleProperty(p_errCtl, p_args)
{
    if (oPolygonList.Items.length != 1)
        p_args.IsValid = false;
    else if (oPolygonList.Items[0].IsCustom)
        p_args.IsValid = false;    
}