var isIE = ((navigator.userAgent.toLowerCase().indexOf("msie") != -1) 
	&& (navigator.userAgent.toLowerCase().indexOf("opera") == -1));
var isIE6 = isIE && (navigator.userAgent.indexOf("MSIE 6.") > -1);

/*-------------------------------------------------
INTRINSIC OBJECT EXTENSIONS
-------------------------------------------------*/
Array.prototype.add = function(item)
{
	this[this.length] = item;
}

Array.prototype.indexOf = function(item)
{
	for (var i = 0; i < this.length; i++)
	{
		if (this[i] == item)
			return i;
	}

	return -1;
}

Array.prototype.contains = function(item)
{
	return this.indexOf(item) > -1;
}

Array.prototype.remove = function(item)
{
	if (this.contains(item))
		this.splice([this.indexOf(item)], 1);
}

Array.prototype.insert = function(index, item)
{
	this.splice(index, 0, item);
}

/*-------------------------------------------------
GENERAL FUNCTIONS
-------------------------------------------------*/
function ConfirmDelete(dataTypeName)
{
	msg = "This action will permanently delete the selected " + dataTypeName
		+ " record from the database. There is no undo function for this "
		+ "action. Click OK to continue or click Cancel to abort the delete "
		+ "action.";
	return(confirm(msg));
}

function ConfirmCascadingDelete(dataTypeName)
{
	msg = "This action will perform a cascading delete on the selected "
		+ dataTypeName + " record, removing it and all associated records "
		+ "from the database.\n\nCAUTION: THIS ACTION MAY HAVE FAR REACHING "
		+ "CONSEQUENCES! THERE IS NO UNDO FUNCTION FOR THIS ACTION!!\n\n"
		+ "Click OK only if you are certain that you want to delete this "
		+ "and all associated records. Otherwise, click Cancel to abort the "
		+ "cascading delete.";
	return(confirm(msg));
}

function DisplayError(snippet, control)
{
	msg = "You must " + snippet + " before continuing. Please try again."
	alert(msg);
	if (control != null) control.focus();
	return(false);
}

function GetCrossBrowserEvent(e)
{
	if (document.all) e = event;
	return e;
}

function GetCrossBrowserSource(e)
{
	var source = null;

	if (e.target)
		source = e.target;
	else if (e.srcElement)
		source = e.srcElement;

	if (source.nodeType == 3) // defeat Safari bug
		source = source.parentNode;

	return source;
}

/*-------------------------------------------------
SHOW PROMPT

Shows a Prompt box containing the specified message
and returns the user's input. RetVal will either be
a string or a null (if Cancel was clicked).
-------------------------------------------------*/
function showPrompt(msg, deflt, maxLen)
{
	//alert("prompt");
	retVal = prompt(msg, deflt)
	if (retVal == "")
	{
		mMsg = "You must enter a value and then click the OK button. To exit without "
			+ "entering a value, click the Cancel button."
		alert(mMsg)
		showPrompt(msg, deflt)
	}
	else if (retVal != null && retVal.length > maxLen)
	{
		tmpVal = retVal.substring(0, maxLen)
		mMsg = "The maximum length for this value is " + maxLen + " characters. Your "
			+ "input exceeds this limit. To automatically truncate your input to the "
			+ "proper length, i.e. \"" + tmpVal + "\", click OK. To return and shorten "
			+ "your input, click Cancel."
		if (confirm(mMsg))
			retVal = tmpVal
		else
			showPrompt(msg, retVal, maxLen)
	}
	return(retVal)
}

/*-------------------------------------------------
CUSTOM VALIDATOR FUNCTIONS
-------------------------------------------------*/
function ValidateText(source, arguments)
{
	arguments.IsValid = validText(arguments.Value);
}

function ValidateWord(source, arguments)
{
	arguments.IsValid = validWord(arguments.Value);
}

function ValidateName(source, arguments)
{
	arguments.IsValid = validName(arguments.Value);
}

function ValidateAddress(source, arguments)
{
	arguments.IsValid = validAddress(arguments.Value);
}

function ValidateTextArea(source, arguments)
{
	textArea = document.getElementById(source.controltovalidate);
	textArea.value = stripHTML(textArea.value);
	arguments.IsValid = validText(textArea.value);
}

function ValidateInteger(source, arguments)
{
    var obj = document.getElementById(source.controltovalidate);
    obj.value = obj.value.replace(/,/gi, "");
    arguments.Value = arguments.Value.replace(/,/gi, ""); 
	arguments.IsValid = validInteger(arguments.Value);
}

function ValidateYear(source, arguments)
{
	arguments.IsValid = validYear(arguments.Value);
}

function ValidateNumber(source, arguments)
{
	arguments.IsValid = validNumber(arguments.Value);
}

function ValidateDate(source, arguments)
	{
	var Test = new Date(arguments.Value)
	arguments.IsValid = ! isNaN(Test)
	}

function ValidateEmail(source, arguments)
	{
	arguments.IsValid = validEmail(arguments.Value);
	}

function ValidateUrl(source, arguments)
{
	RE = /^https?:\/\//i
	el = document.getElementById(source.controltovalidate);
	if (!RE.test(arguments.Value)) el.value = "http://" + arguments.Value;
	RE = /^https?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?$/
	arguments.IsValid = RE.test(el.value);
}

function ValidateUrlClassic(el)
{
	RE = /^https?:\/\//i
	if (!RE.test(el.value)) el.value = "http://" + el.value;
	RE = /^https?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?$/
	return RE.test(el.value);
}

function ValidateZipCode(source, arguments)
{
	arguments.IsValid = validZipCode(arguments.Value);
}

function ValidateFutureDate(source, arguments)
{
	Date1 = new Date(arguments.Value);
	Date2 = new Date();
	if (Date1 > Date2)
		arguments.IsValid = true;
	else
		arguments.IsValid = false;
}

function ValidateTime(source, arguments)
{
	RE = /^(1[0-2]|[1-9])\:[0-5][0-9] ?(a|p)m$/i
	arguments.IsValid = RE.test(arguments.Value);
}

function ValidateUSPhone(source, arguments)
{
	Phone = arguments.Value;
	TmpVal = "";
	for (var i = 0; i < Phone.length; i++)
	{
		if (Phone.charAt(i) >= "0" && Phone.charAt(i) <= "9")
			TmpVal += Phone.charAt(i);
	}
	if (TmpVal.length != 10)
		arguments.IsValid = false;
	else
	{
		Phone = TmpVal.substr(0, 3) + "-" + TmpVal.substr(3, 3) + "-" + TmpVal.substr(6, 4);
		RE = /^[1-9][0-9]{2}\-[1-9][0-9]{2}\-[0-9]{4}$/
		if (RE.test(Phone))
		{
			document.forms[0].elements[source.controltovalidate].value = Phone;
			arguments.IsValid = true;
		}
		else
			arguments.IsValid = false;
	}
}

function ValidateAnyPhone(source, arguments)
{
	arguments.IsValid = validAnyPhone(arguments.Value);
}
	
function ValidateEmailArray(source, arguments)
{
	var isValid = true;
	aryStr = arguments.Value.split(",")
	for (var i = 0; i < aryStr.length; i++)
	{
		if (! validEmail(Trim(aryStr[i])))
		{
			isValid = false
			break
		}
	}
	arguments.IsValid = isValid;
}

function ValidateUserName(source, arguments)
{
	arguments.IsValid = validUserName(arguments.Value);
}

function ValidateWeakPassword(source, arguments) 
{
    arguments.IsValid = validWeakPassword(arguments.Value);
}

function ValidateMediumPassword(source, arguments) 
{
    arguments.IsValid = validMediumPassword(arguments.Value);
}

function ValidateStrongPassword(source, arguments)
{
	arguments.IsValid = validStrongPassword(arguments.Value);
}
	
function ValidateVIN(source, arguments)
{
	arguments.IsValid = validVIN(arguments.Value);
}

function ValidateImageExtension(source, arguments)
{
	arguments.IsValid = validImageExtension(arguments.Value);
}

function ValidateImageExtensionWithFlash(source, arguments)
{
	arguments.IsValid = validImageExtension(arguments.Value, true);
}

function ValidatePDFExtension(source, arguments)
{
	arguments.IsValid = validPDFExtension(arguments.Value);
}

function ValidateDocumentExtension(source, arguments)
{ 
	if (arguments.Value != "")
	{
		arguments.IsValid  = validDocumentExtension(arguments.Value);
	}
}

function VerifyPhones(source, arguments)
{
	arguments.IsValid = ! (document.getElementById("DayPhone").value == "" && document.getElementById("EveningPhone").value == "");
}

/*-------------------------------------------------
REGULAR EXPRESSION AND OTHER VALIDATORS
-------------------------------------------------*/
function validText(val)	//allows all characters except those excluded
{
	RE = /^[^\<\>\@]+$/i;
	return RE.test(Trim(val));
}

function validWord(val)
{
	RE = /^[\w]+$/i;
	return RE.test(Trim(val));
}

function validName(val)
{
	RE = /^[a-z"\-'\,\. ]+$/i;
	return RE.test(Trim(val));
}

function validAddress(val)
{
	RE = /^[0-9a-z"-'\#\(\)\.\,\:\; ]+$/i;
	return RE.test(Trim(val));
}

function validYear(val)
{
	RE = /^\d{4}$/
	if (! RE.test(val))
		return false
	else
	{
		if (val < 1900 || val > 2100)
			return false
	}
	return true
}
	
function validInteger(val)
{
	RE = /^\-?\d+$/
	return RE.test(val)
}
	
function validNumber(val)
{
	RE = /^(\d{1,3}\,?(\d{3}\,?)*\d{3}(\.\d+)?|\d{1,3}(\.\d+)?|\.\d+)$/
	return RE.test(val)
}
	
function validDate(el)
{
	tmpDate = new Date(el.value)
	if (isNaN(tmpDate))
		return false
	else
	{
		Mo = tmpDate.getMonth() + 1
		if (Mo < 10) Mo = "0" + Mo.toString()
		Da = tmpDate.getDate()
		if (Da < 10) Da = "0" + Da.toString()
		Yr = tmpDate.getFullYear()
		if (Yr < 1950) Yr += 100
		el.value = Mo + "/" + Da + "/" + Yr
		return true
	}
}
	
function validEmail(val)
{
	RE = /^[A-Z0-9\.\_\-]+@([A-Z0-9\.\-]+\.)+[A-Z0-9\.\-]{2,4}$/i
	return RE.test(val)
}
	
function validEmailArray(Str)
{
	aryStr = Str.split(",")
	for (i = 0; i < aryStr.length; i++)
		{
		if (! validEmail(Trim(aryStr[i])))
			return false
		}
	return true
}
	
function validZipCode(val)
{
	RE = /^[0-9]{5}(\-[0-9]{4})?$/
	return RE.test(val)
}
	
function validUrl(val)
{
	RE = /^https?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?$/
	return RE.test(val);
}

function validVIN(val)
{
	RE = /^[0-9a-z]{17}$/i
	return RE.test(val);
}

function validImageExtension(val, allowFlash)
{
	if (allowFlash == true)
		RE = /\.(jpg)|(gif)|(swf)$/i
	else
		RE = /\.(jpg)|(gif)$/i
		
	return RE.test(val);
}

function validPDFExtension(val)
{
	RE = /\.pdf$/i
	return RE.test(val);
}

function validDocumentExtension(val)
{  
	if (val != "")
	{
		RE = /\.(doc)|(pdf)$/i
		return RE.test(val);
	}
}

function validHexColor(val)
{
	RE = /^\#[0-9a-f]{6}$/i;
	return RE.test(val);
}

function validUserName(val)
{
	RE = /^[a-z0-9_-]{6,20}$/i;
	return RE.test(val);
}

function validWeakPassword(val) 
{
    var rePassword = /^[0-9a-z]{6,20}$/i;
    return rePassword.test(val);
}

function validMediumPassword(val) 
{
    var isValid = true;

    if (val.length < 6 || val.length > 20)
        isValid = false;
    else {
        var reLower = /[a-z]/;
        var reUpper = /[A-Z]/;
        var reNum = /[0-9]/;

        isValid = reLower.test(val) && reUpper.test(val) && reNum.test(val);
    }

    return isValid;
}

function validStrongPassword(val)
{
	var isValid = true;
	
	if (val.length < 7 || val.length > 20)
		isValid = false;
	else
	{
		var reLower = /[a-z]/;
		var reUpper = /[A-Z]/;
		var reNum = /[0-9]/;
		var reSpec = /[`~!@#$%^&\*\(\)_\-+=\{\[\}\};:'",<\.>\?\/|\\]/;
		
		isValid = reLower.test(val) && reUpper.test(val) && reNum.test(val) && reSpec.test(val);
	}
	
	return isValid;
}

function validAnyPhone(val)
{
	RE = /^[0-9\-\(\) x]{10,}$/i;
	return RE.test(Trim(val));
}

function testLength(el, len)
	{
	val = el.value
	if (val.length > len)
		{
		msg = "Your input exceeds the " + len + " character limit for this field. "
			+ "Please adjust your input and try again."
		alert(msg)
		el.focus()
		return false
		}
	return true
	}
	
function stripHTML(val)
{
	RE = /<[^>]+>/g;
	val = val.replace(RE, "");
	return val;
}
	
function DayName(DayVal)
	{
	switch (DayVal)
		{
		case 0:
			return "Sunday"
			break
		case 1:
			return "Monday"
			break
		case 2:
			return "Tuesday"
			break
		case 3:
			return "Wednesday"
			break
		case 4:
			return "Thursday"
			break
		case 5:
			return "Friday"
			break
		case 6:
			return "Saturday"
			break
		}
	}
	
function MonthName(MonthVal)
	{
	switch (MonthVal)
		{
		case 0:
			return "January"
			break
		case 1:
			return "February"
			break
		case 2:
			return "March"
			break
		case 3:
			return "April"
			break
		case 4:
			return "May"
			break
		case 5:
			return "June"
			break
		case 6:
			return "July"
			break
		case 7:
			return "August"
			break
		case 8:
			return "September"
			break
		case 9:
			return "October"
			break
		case 10:
			return "November"
			break
		case 11:
			return "December"
			break
		}
	}

function FormatTime(DateVal)
	{
	AP = "AM"
	Hr = DateVal.getHours()
	if (Hr >= 12) 
		{
		Hr -= 12
		AP = "PM"
		}
	if (Hr < 10) Hr = "0" + Hr
	Min = DateVal.getMinutes()
	if (Min < 10) Min = "0" + Min
	return Hr + ":" + Min + " " + AP
	}
	
function IsFutureDate(uDate)
{
	Now = new Date();
	UserDate = new Date(uDate);
	if (UserDate > Now)
		return true
	else
		return false
}

function SafeString(text)
{
	return escape(Trim(text));
}

function Trim(Str)
{
	Str = LeftTrim(Str)
	return RightTrim(Str)
}

function LeftTrim(Str)
{
	for (i = 0; i < Str.length; i++)
	{
		if (Str.charAt(i) != " ")
			break
	}
	return Str.substring(i, Str.length)
}
	
function RightTrim(Str)
{
	for (i = Str.length - 1; i >= 0; i--)
	{
		if (Str.charAt(i) != " ")
			break
	}
	return Str.substring(0, i + 1)
}

function AppendList(list, value, text)
{
	var newOption = document.createElement("option");
	newOption.value = value;
	newOption.text = text;
	try
	{
		list.add(newOption, null);	//standards compliant
	}
	catch (ex)
	{
		list.add(newOption);		//IE only
	}
}

function InsertList(list, value, text, index)
{
	var oldOption = list.options[index];
	var newOption = document.createElement("option");
	newOption.value = value;
	newOption.text = text;
	try
	{
		list.add(newOption, oldOption);	//standards compliant
	}
	catch (ex)
	{
		list.add(newOption, index);		//IE only
	}
}

function ClearList(list)
{
	for (var i = list.options.length - 1; i >= 0; i--)
	{
		RemoveList(list, i);
	}
}

function RemoveList(list, index)
{
	list.remove(index);
}

function GetCookie(keyName)
{
	var _cookies = document.cookie.split(";");
	var _value = null;
	for (var i = 0; i < _cookies.length; i++)
	{
		if (_cookies[i].indexOf(keyName) > -1)
		{
			_split = _cookies[i].split("=");
			if (_split.length == 2)
				_value = Trim(_split[1]);
			break
		}
	}
	return _value;
}

function DeleteCookie(keyName) 
{
	document.cookie = keyName + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
} 
/*-------------------------------------------------
SHOW POP UP

This function generates a new pop-up window based
on the referenced arguments. If any pop-up window
is currently open, it closes that window and opens
the requested window.
-------------------------------------------------*/

var nWin = null

function ShowPopUp(URL, Name, Height, Width, Top, Left, Status, Toolbar, Menubar, Location, Resizable, Scrollbars)
{
	if (nWin == null)
	{
		nWin = window.open(URL, Name, "height=" + Height + ",width=" + Width 
			+ ",top=" + Top + ",left=" + Left + ",status=" + Status 
			+ ",toolbar=" + Toolbar + ",menubar=" + Menubar
			+ ",location=" + Location + ",resizable=" + Resizable + ",scrollbars=" + Scrollbars)
	}
	else
	{
		CloseNWin()
		ShowPopUp(URL, Name, Height, Width, Top, Left, Status, Toolbar, Menubar, Location, Resizable, Scrollbars)
	}	
}

function CenterHorz(width)
{
	return (parseInt(GetScreenLeft() + ((GetWindowWidth() - width) / 2)))
}

function CenterVert(height)
{
	//the height is the client height but add 75 more for the title bar, address
	//bar and status bar
	var IESlop = 0;
	if (isIE) IESlop = 75;

	return (parseInt(GetScreenTop() + ((GetWindowHeight() - (height + IESlop)) / 2)))
}

function CenterClientHorz(width)
{
	return (parseInt(((GetWindowWidth() - width) / 2)))
}

function CenterClientVert(height)
{
	//25 is the apprx. size of the title bar which is not part of the pop-up height
	var IESlop = 0;
	if (isIE) IESlop = 25;

	return (parseInt(((GetWindowHeight() - (height + IESlop)) / 2)))
}

function CloseNWin()
{
   if (nWin != null)
    {
      nWin.close()
      nWin = null
    }
}
   
function CloseWindow()
{
	opener.nWin = null
	window.close()
}

function GetWindowHeight()
{
	var height = 0;
	
	if (typeof(top.window.innerHeight) != "undefined")
		height = top.window.innerHeight;
	else if (top.document.documentElement.clientHeight > 0)
		height = top.document.documentElement.clientHeight;
	else
		height = top.document.body.clientHeight;
		
	return height;
}

function GetWindowWidth()
{
	var width = 0;
	
	if (typeof(top.window.innerWidth) != "undefined")
		width = top.window.innerWidth;
	else if (top.document.documentElement.clientWidth > 0)
		width = top.document.documentElement.clientWidth;
	else
		width = top.document.body.clientWidth;
		
	return width;
}

function GetScreenTop()
{
	var scrnTop = top.window.screenTop;
	if (!isIE) scrnTop = top.window.screenY;		
	if (isNaN(scrnTop)) scrnTop = 0;
	return scrnTop;
}

function GetScreenLeft()
{
	var scrnLeft = top.window.screenLeft;	
	if (!isIE) scrnLeft = top.window.screenX;		
	if (isNaN(scrnLeft)) scrnLeft = 0;
	return scrnLeft;
}

function GetViewableDimensions()
{
	//see http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

	var viewableWidth = 0, viewableHeight = 0;

	if (typeof (window.innerWidth) == 'number')
	{
		//Non-IE
		viewableWidth = window.innerWidth;
		viewableHeight = window.innerHeight;
	}
	else if (document.documentElement && (document.documentElement.viewableWidth || document.documentElement.clientHeight))
	{
		//IE 6+ in 'standards compliant mode'
		viewableWidth = document.documentElement.clientWidth;
		viewableHeight = document.documentElement.clientHeight;
	}
	else if (document.body && (document.body.viewableWidth || document.body.clientHeight))
	{
		//IE 4 compatible
		viewableWidth = document.body.clientWidth;
		viewableHeight = document.body.clientHeight;
	}

	return [viewableWidth, viewableHeight];
}

function GetScrollDimensions()
{
	//see http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

	var leftScroll = 0, topScroll = 0;

	if (typeof (window.pageYOffset) == 'number')
	{
		//Netscape compliant
		topScroll = window.pageYOffset;
		leftScroll = window.pageXOffset;
	}
	else if (document.body && (document.body.scrollLeft || document.body.scrollTop))
	{
		//DOM compliant
		topScroll = document.body.scrollTop;
		leftScroll = document.body.scrollLeft;
	}
	else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
	{
		//IE6 standards compliant mode
		topScroll = document.documentElement.scrollTop;
		leftScroll = document.documentElement.scrollLeft;
	}

	return [leftScroll, topScroll];
}

var CallingUpdatePanel = null;

function ClosePopup()
{
	if (CallingUpdatePanel != null)
	{
		__doPostBack(CallingUpdatePanel, CallingUpdatePanel);
		CallingUpdatePanel = null;
	}
	
	setTimeout('CloseNWin()', 200);
}

function ShowPhonePopup(callingPanel, businessId, phoneId)
{
	CallingUpdatePanel = callingPanel;
	
	var url = "PhonePopup.aspx?BusinessId=" + businessId + "&PhoneId=" + phoneId;
	var name = "PhonePopup";
	var width = 500;
	var height = 250;	
	var topVal = CenterVert(height);
	var leftVal = CenterHorz(width);
	var status = "no";
	var toolbar = "no";
	var menubar = "no";
	var location = "no";
	var resizable = "no";
	var scrollbars = "no";

	ShowPopUp(url, name, height, width, topVal, leftVal, status, 
		toolbar, menubar, location, resizable, scrollbars)
}

//function ShowModalPopup()
//{
//	if (activePopup)
//	{
//		var back = document.getElementById("PopupBackground");

//		var bgHeight = "";
//		if (document.body.offsetHeight > GetWindowHeight())
//			bgHeight = (document.body.offsetHeight + 50) + "px";
//		else
//			bgHeight = "100%";
//		back.style.height = bgHeight;
//		back.style.display = "block";

//		activePopup.style.display = "block";
//		//alert(activePopup.offsetWidth + " x " + activePopup.offsetHeight);

//		activePopup.style.left = CenterClientHorz(activePopup.offsetWidth) + "px";
//		activePopup.style.top = CenterClientVert(activePopup.offsetHeight) + "px";
//	}
//}

