var browserName=navigator.appName.toLowerCase();; 
var isIE = browserName.toLowerCase().indexOf("explorer")>-1

//************************************************************
//* Tests whether the given argument is empty or null
//************************************************************
function isnull(arg) {
	if(typeof(arg) == "object"){
		if(arg==null)
			return true;
		else
			return false;
	}

	arg = arg+'';
	var rv =(arg == '' || arg == 'null' || arg == 'undefined'); 
	return rv;
}

//************************************************************
//* Tests whether the given argument is a valid date
//************************************************************
function isDate(sDate) {
	var scratch = new Date(sDate);
	if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date") {
		return false;
	} 
	else {
		return true;
	}
}

function isValidTime(timeStr) 
{
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		alert("Time is not in a valid format.");
		return false;
	}
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];

	if (second=="")
		second = null; 
	
	if (ampm=="")
		ampm = null;

	if (hour < 0  || hour > 23) {
		alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
		return false;
	}
	
	if (hour <= 12 && ampm == null) {
		if (confirm("Please indicate which time format you are using. OK = Standard Time, CANCEL = Military Time")) {
			alert("You must specify AM or PM.");
			return false;
	   }
	}
	
	if  (hour > 12 && ampm != null) {
		alert("You can't specify AM or PM for military time.");
		return false;
	}
	
	if (minute<0 || minute > 59) {
		alert ("Minute must be between 0 and 59.");
		return false;
	}
	
	if (second != null && (second < 0 || second > 59)) {
		alert ("Second must be between 0 and 59.");
		return false;
	}
	
	return true;
}

//************************************************************
//* Padding the given value with zero beffor the number
//************************************************************
function zeroPad(v, len){ 
	if (isnull(len)) len = 2;
	
	var str = new String(v);
	while (str.length < len) str = '0' + str;
	return str;
}

//************************************************************
//* null value function
//************************************************************
function nvl() {
	for (var i=0; i<arguments.length; i++)
		if (!isnull(arguments[i])) 
			return arguments[i];
	
	return "";
}

//************************************************************
//* Removes white spaces from beginning and end of a string.
//************************************************************
function trim(str){
	try {
		return str.replace(/^\s+|\s+$/g,'');
	}
	catch (e) {return str;}
}


//************************************************************
//* set the url as the requested
//************************************************************
function go(address) {
	window.location=address
}

/////////////////////////////////////////////////////////////////////////////////////////
function escapeXmlChars(str) {
	str = str + '';
	return (str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;"))
}

function unescapeXmlChars(str) {
	str = str + '';
	return (str.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&"))
}


/////////////////////////////////////////////////////////////////////////////////////////
function delCookie(cookieName)
{
	var t = new Date()
	set_cookie(cookieName,"",(t.getFullYear()-30),t.getMonth(),t.getDate(),"/")
	//redirect the member to the home page (root)
	//the setTimeout is the only way we get it to work on all browsers and OS 
	setTimeout( "go('/')", 0 );
}

/////////////////////////////////////////////////////////////////////////////////////////
//* there are 2 function of the get cookie because i dont want to search all the references for each of them
/////////////////////////////////////////////////////////////////////////////////////////
//Chack If there is a Cookie
function getCookie(sName){
	// cookies are separated by semicolons
	var aCookie = document.cookie.split(";");
	for (var i=0; i < aCookie.length; i++){
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = aCookie[i].split("=");
		if (sName == trim(aCrumb[0]))return unescape(aCrumb[1]);
	}
	return null;// a cookie with the requested name does not exist
}

/////////////////////////////////////////////////////////////////////////////////////////
function get_cookie ( cookie_name){
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );
  if ( results ){
	return ( unescape ( results[1] ) );
  }
  else return null;
}

/////////////////////////////////////////////////////////////////////////////////////////
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure ){
	var cookie_string = name + "=" +  value ;
	if ( exp_y ) {
		var expires = new Date ( exp_y, exp_m, exp_d );
		cookie_string += "; expires=" + expires.toGMTString();
	}
	if ( path ) cookie_string += "; path=" + escape ( path );
	if ( domain ) cookie_string += "; domain=" + escape ( domain );
	if ( secure ) cookie_string += "; secure";
	//alert(cookie_string)
	document.cookie = cookie_string;
}

/*
/////////////////////////////////////////////////////////////////////////////////////////
//this is from the site
function saveUserLang(obj)
{ 
	set_cookie("siteLang", escape(obj.value),2020,12,25,"/")
	window.location.reload();
} 
////////////////////////////////////
//this is from the admin
function saveUserLang(obj)
{ 
	setCookie("userLang" ,obj.value);
	window.location.href = window.location;
} 
*/
/////////////////////////////////////////////////////////////////////////////////////////
function openWindow(url,param,wName){
	wName = nvl(wName,"defWin")
	//param = nvl(param,"scrollbars=no,toolbar=no,resizable=0,left=0,top=0,width=550,height=450");
	if(isnull(param)) 
		var win = window.open(url, wName);
	else
		var win = window.open(url, wName ,param);
	win.focus();
}

/////////////////////////////////////////////////////////////////////////////////////////
var lastObjID = "";
function showHideDiv(objID){
	try{
		if(objID != lastObjID)
			document.getElementById(lastObjID).style.display="none"
	}
	catch(e){}
	if(document.getElementById(objID).style.display=="none"){
		document.getElementById(objID).style.display=""
	}
	else{
		document.getElementById(objID).style.display="none"
	}
	lastObjID = objID;
}

////////////////////////////////////////////////////////////////////////////////////////////////////

var activeElementID = "";
function showActiveElement(ElementID){
	try{
		if(ElementID != activeElementID){
			document.getElementById(activeElementID).style.display="none"
		}
	}
	catch(e){}
	
	document.getElementById(ElementID).style.display="";
	activeElementID = ElementID;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
var arrImages = [];
var imgSrc = "";
function imgOnOff(img,on){
	if(isnull(arrImages[img.src])){
		arrImages[img.src] = new Image();
		arrImages[img.src].src = img.src;
	}
	//if(arrImages[img.src]==true) alert()
	imgSrc=arrImages[img.src].src;//img.src
	imgSrc = imgSrc.toLowerCase( )
	if(on){
		imageOn=imgSrc.substring(0,imgSrc.indexOf("off.gif")) + "on.gif"
		//document.images[img.name].src =imageOn
		img.src = imageOn;
	}
	else{
		imageOff=imgSrc.substring(0,imgSrc.indexOf("on.gif")) + "off.gif"
		//document.images[img.name].src =imageOff
		img.src = imageOff;
	}
}
//this function is for the menues, where we cant force the user to add ".on" and ".off" to the names
function toggleImg(imgId, imgSrc)
{
	var img = document.getElementById(imgId);
	if(isnull(arrImages[img.src])){
		arrImages[img.src] = new Image();
		arrImages[img.src].src = img.src;
	}
	img.src = imgSrc;
}


//************************************************************
// Return a formatted dialog features string
//************************************************************
function dlgFeatures(w, h, win) {
	if (win) {
		var x = (!isnull(win.screenLeft) ? win.screenLeft : win.screenX) + (win.document.body.clientWidth-w)/2;
		var y = (!isnull(win.screenTop) ? win.screenTop : win.screenY)  + (win.document.body.clientHeight-h)/2;
	}
	else {
		var x = (!isnull(window.screenLeft) ? window.screenLeft : window.screenX) + (document.body.clientWidth-w)/2;
		var y = (!isnull(window.screenTop) ? window.screenTop : window.screenY)  + (document.body.clientHeight-h)/2;
	}
	if (x > screen.availWidth || y > screen.availHeight) {
		x = (screen.availWidth -  w)/2;
		y = (screen.availHeight - h)/2;
	}

	return 'dialogLeft:'+x+'px;dialogTop:'+y+'px;'+
			 'dialogWidth:'+w+'px;dialogHeight:'+h+'px;'+
			 'status:no; scroll:no; edge:no;help:no;'
}

function alertSize() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		myWidth = window.innerWidth; myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth ||document.documentElement.clientHeight ) ) {
		myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
	}
	window.alert( 'Width = ' + myWidth + ' and height = ' + myHeight );
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset; scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop; scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		scrOfY = document.documentElement.scrollTop; scrOfX = document.documentElement.scrollLeft;
	}
	window.alert( 'Horizontal scrolling = ' + scrOfX + '\nVertical scrolling = ' + scrOfY );
}

/////////////////////////////////////////////////////////////////////////////////////////
//
function cutString(strParam,len,addDots,notComplite){
	//return only 'len' chars from the 'str' param, and if 'addDots' = true added 3 ... in the end
	if(isnull(strParam) || len== 0 ) return "";
	if(isnull(notComplite)) notComplite=false
	str = strParam//cleanHtmlTags(strParam)
	if (String(str).length <= len) return str;

	var temp = String(str).substring(0,len);
	if(addDots == true && (String(str).length-len)<3){
		return str
	}
	var temp2 = "";

	if(!notComplite){
		// complite the last word...
		for (var i = len;i < String(str).length;i++){
			temp2 = String(str).substring(i,i+1);
			if (temp2 == ' ') break;
			temp +=temp2
		}
	}
	//alert(String(str).length + "\n" + len + "\n" + temp + "\n" + temp.length)
	return temp.length < str.length && addDots == true ? temp + "..." : temp;
}

/////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////
///Add to favorits/ bookmark. need to be upgraded for all browsers
/////////////////////////////////////////////////////////////////////////////////////////
function addFavorite(url,title)
{
	if (window.sidebar) {
		// Mozilla Firefox Bookmark		
		window.sidebar.addPanel(title, url,"");	
	} 
	else if( window.external ) { 
		// IE Favorite		
		window.external.AddFavorite( url, title); 
	}	
	else { 
		alert("You need to click CTRL+D to bookmark us."); 
	}
}

//warper function that sourund the givven string with single qouting mark
function qoute1(str)
{
	return "'" + str + "'";
}
//warper function that sourund the givven string with double qouting mark
function qoute2(str)
{
	return '"' + str + '"';
}

//////////////////////////////////////////////////////////////////////////////
//input rype="radio" handeling : start
//////////////////////////////////////////////////////////////////////////////

//retrive the selected value from a radiolist object
function getRadioSelectedValue(radioList, byName, arrName)
{
	var options;
	if(byName)
		options  = document.getElementsByName(radioList);
	else
		options  = document.getElementById(radioList).getElementsByTagName("input");
		
	
	for(i=0;i<options.length;i++)
	{
		var opt = options[i];
		if(opt.checked)
		{
			//if byName=true, that means we are using the radiobutton control inside a databinded object - like repeater- and not a radiobuttonlist
			//in that case, we must send also the name of the array we created for the client that holds the values
			//se the use of that in /Admin/Console/settings/controls/templates_skins/container.ascx control
			if(byName)
				return arrName[i];
				
			return opt.value;
		}
	}
}

//set a radio list value
function setRadioSelectedValue(radioList, value)
{
	var options = document.getElementById(radioList).getElementsByTagName("input");
	for(i=0;i<options.length;i++){
		var opt = options[i];
		if(opt.value == value)
			opt.checked = true;
	}
}


//////////////////////////////////////////////////////////////////////////////
//input type="radio" handeling : end
//////////////////////////////////////////////////////////////////////////////


//C# String.Foramt() in java script 
String.format = function(text)
{
    //check if there are two arguments in the arguments list
    if ( arguments.length <= 1 )
        //if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return text;

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ )
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ]);

    return text;
};

//Ajax pro problem with sync calles (no callback func)
function AjaxTimeout() 
{ 
	//set the timeout to 3000 secondes (50 minutes) insted of 15 seconds
	//i did it cause all of a sudden the code below stoped working :-(
	AjaxPro.timeoutPeriod = 3000*1000;
	return;
	
	if(typeof AjaxPro != "undefined" && AjaxPro !== null){ 
		AjaxPro.timeoutPeriod = 3000000000; 
		AjaxPro.onTimeout = function(b,res){ 
			   // alert('Timeout'); 
			   var s ="0"; 
		} 
		
		AjaxPro.onError = function(res){ 
			alert('error'); 
		} 
		
		var r = "undefined"; 
		if (typeof(this.onTimeout ||AjaxPro.onTimeout) == "function") 
			r = (this.onTimeout || AjaxPro.onTimeout)(this.duration, this); //this.onTimeout(this.duration, this); 

	} 
} 

//we use the form_is_dirty flag in the edit template to confirm exit from unsaved record
//but because we add the onchange event to all our validation controls, we need this function here in the stdlib
var form_is_dirty=false;
function setDirty(val)
{
	form_is_dirty=val;
}
