// Common functions
/* ************************************* 
   ** popup window on scroll location **
   ************************************* */
window.onscroll = doOnScroll;

var scroll_interval;
var S;
var W = document.documentElement.offsetWidth;
var theHeight = window.innerHeight;
var destenation;
var curr_popup = null;
var ChatWindows = new Array();
var InitiatedWindows = new Array();
var IE = window.navigator.appName.toLowerCase().indexOf("explorer")>-1;
var IsSubScriber;
var IsDelegatedSubScriber;
var topMenuxPosCorrection;
var topMenuxPosCorrectionDefault;

function CheckForBadLogin() { 
	try {
		if (typeof badlogin == "boolean" && badlogin == true) {
			OpenBadLoginPopup();
		}
	} catch(e) {}
	try {
		if (typeof inactivelogin == "boolean" && inactivelogin == true) {
			OpenInactiveLoginPopup();
		}
	} catch(e) {}
	
}

function HandelSubScribtionExpiration() {
    location.href = httpslink + 'secure/subscription.aspx?rs=1';
}

function doOnScroll() {
	S=document.body.scrollTop;
	if (window.innerHeight)
		theHeight=window.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		theHeight=document.documentElement.clientHeight;
	else if (document.body)
		theHeight=document.body.clientHeight;
	if (curr_popup != null){
		var k = document.getElementById(curr_popup)
		
		destenation = Math.round(theHeight/2 - k.offsetHeight/2)+ S;
	}
}

function setPopupY(){

	if (curr_popup != null){
		var k = document.getElementById(curr_popup)
		destenation = Math.round(theHeight/2 - k.offsetHeight/2)+ S;
		if (destenation < document.body.scrollTop) destenation = document.body.scrollTop;
		if (destenation + k.offsetHeight > document.body.scrollHeight) destenation = document.body.scrollHeight - k.offsetHeight;
	}
	try { 
		var k = document.getElementById(curr_popup);
		var T = k.offsetTop;
		k.style.top= (T-Math.round((T-destenation)/3))+"px"; 
	} catch(e) {}	
}


/* *************************************
   *** Custom Radiobutton management ***
   ************************************* */

var RADIOBUTTON_ON = new Image();
var RADIOBUTTON_OFF = new Image();
RADIOBUTTON_ON.src = "/img/radioOn.gif";
RADIOBUTTON_OFF.src = "/img/radioOff.gif";

var RadiobuttonRegistry = new Object();
RadiobuttonRegistry.Items = new Array();
RadiobuttonRegistry.GetGroup = function(groupName) {
	// Returns all radiobuttons belonging to a group
	var ret = new Array();
	for (var i=0;i<this.Items.length;i++) {
		if (this.Items[i].Group == groupName) ret.push(this.Items[i]);
	}
	return ret;
}
RadiobuttonRegistry.Mark = function(objectRef) {
	// Fetches the group and "selects" the specified object
	var group = this.GetGroup(objectRef.Controller.Group);
	for (var i=0;i<group.length;i++) {
		if (group[i].Element == objectRef) {
			group[i].Element.src = RADIOBUTTON_ON.src;
			document.getElementById(group[i].Hidden).value = group[i].Value;
			try {
				var p1 = group[i].Element.parentNode;
				var p2 = p1.parentNode;
				if (p1.tagName.toLowerCase() == "div" && typeof p1.id != "undefined" && p1.id.toLowerCase().indexOf("wrap") > -1) {
					p1.style.border = "";
				} else if (p2.tagName.toLowerCase() == "div" && typeof p2.id != "undefined" && p2.id.toLowerCase().indexOf("wrap") > -1) {
					p2.style.border = "";
				}
			} catch(e) {}
		} else {
			group[i].Element.src = RADIOBUTTON_OFF.src;
		}
	}
}

function Radiobutton(obj,groupname,hidden,value) {
	this.Element = obj;
	this.Group = groupname;
	this.Hidden = hidden;
	this.Value = value;
	this.Element.Controller = this;
}

function RegisterRadioButton(obj,groupname,hiddenid,value) {
	// Registers an object as radiobutton for provided groupname. Selecting the radiobutton will change the value of the hidden to the provided value
	if (typeof obj == "string" || typeof obj.tagName == "undefined") obj = document.getElementById(obj);
	if (obj == null) return;
	var rad = new Radiobutton(obj,groupname,hiddenid,value);
	obj.onclick = RadiobuttonClick;
	RadiobuttonRegistry.Items.push(rad);
}

function RadiobuttonClick(ev) {
	if (typeof ev != "undefined") {
		var source = ev.target;
	} else {
		var source = event.srcElement;
	}
	if (typeof source.Controller != "undefined" && source.Controller != null) {
		// Valid radiobutton
		RadiobuttonRegistry.Mark(source);
	}
	if (source.getAttribute("runAlso") != null) {
		try {
			eval(source.getAttribute("runAlso"));
		} catch(e) {}
	}
}

/* *************************************
   ***** Custom Checkbox management ****
   ************************************* */

var CHECKBOX_OFF = new Image();
var CHECKBOX_ON = new Image();
CHECKBOX_OFF.src = "/img/checkboxOff.gif";
CHECKBOX_ON.src = "/img/checkboxOn.gif";

var CheckboxRegistry = new Object();
CheckboxRegistry.Items = new Array();
CheckboxRegistry.GetItem = function(name) {
	for (var i=0;i<CheckboxRegistry.Items.length;i++) {
		if (CheckboxRegistry.Items[i].Name == name) return CheckboxRegistry.Items[i];
	}
	return null;
}
CheckboxRegistry.Register = function(name, cbImgRefId, cbTxtRefId, defStateBool, hdnRefId) {
	// Check if exists
	var exists = CheckboxRegistry.GetItem(name);
	if (exists == null) {
		// Not present, continue
		try {
			var img = (typeof cbImgRefId == "string")?document.getElementById(cbImgRefId):cbImgRefId;
			var lbl = (typeof cbTxtRefId == "string")?document.getElementById(cbTxtRefId):cbTxtRefId;
			var hdn = (typeof hdnRefId == "string")?document.getElementById(hdnRefId):hdnRefId;
			if (hdn == null) hdn = hdnRefId;		// Special case for special checkboxes
			var cb = new Checkbox(name, img, lbl, defStateBool, hdn);
			// Assign callbacks
			cb.Graphics.Controller = cb;
			cb.Label.Controller = cb;
			// Assign handlers
			cb.Label.onclick = CheckboxClick;
			CheckboxRegistry.Items.push(cb);
		} catch(e) {
		}
	}
}

CheckboxRegistry.UnregisterAll = function() {
	CheckboxRegistry.Items = new Array();
}

function CheckboxClick(ev) {
	if (this.Controller != null) {
		// Check hidden
		this.Controller.State = !this.Controller.State;
		this.Controller.Graphics.src = (this.Controller.State == false)?CHECKBOX_OFF.src:CHECKBOX_ON.src;
		try {
			var p1 = this.Controller.Graphics.parentNode.parentNode.parentNode;
			var p2 = this.Controller.Graphics.parentNode.parentNode;
			if (p1.tagName.toLowerCase() == "div" && typeof p1.id != "undefined" && p1.id.toLowerCase().indexOf("wrap") > -1) {
				p1.style.border = "";
			} else if (p2.tagName.toLowerCase() == "div" && typeof p2.id != "undefined" && p2.id.toLowerCase().indexOf("wrap") > -1) {
				p2.style.border = "";
			}
		} catch(e) {}
		if (this.Controller.Hidden != null) {
			this.Controller.Hidden.value = (this.Controller.State == true)?"1":"0";
		} else {
			this.Controller.AlternateHandler(this.Controller);
		}
	}
}

function Checkbox(name, gfxRef, txtRef, defState, hdnRef) {
	this.Name = name;
	this.State = defState;
	this.Graphics = gfxRef;
	this.Label = txtRef;
	if (typeof hdnRef != "string" && typeof hdnRef.value != "undefined") {
		// Linked to hidden field
		this.Hidden = hdnRef;
		this.AlternateHandler = null;
	} else {
		// Linked to special function
		this.Hidden = null;
		this.AlternateHandler = hdnRef;
	}
}

/** ENTER Keypress checkup function **/

function CheckEvent13(ev,func) {
	var isIE = false;
	if (navigator.appName.indexOf("Microsoft") > -1 || navigator.appName.indexOf("IE") > -1) {
		isIE = true;
	}
	if ((isIE && event.keyCode == 13) || (!isIE && ev.which == 13)) {
		if (isIE) {
			event.cancelBubble = true;
		} else {
			ev.preventDefault();
			ev.stopPropagation();
		}
		return func();
	}
}

/** Floating menu placer **/
function returnDocumentName() {
    var file_name = document.location.href;
    var end = file_name.lastIndexOf(".");
    return file_name.substring(file_name.lastIndexOf("/") + 1, end);
}

function RegisterElementForFloatingMenu(objid) {
	//alert()
    var obj = document.getElementById(objid);

	if (obj)
	    obj.onmouseover = HandleShowFloatingMenu;
}

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.    
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    } return rv;
}

function HandleShowFloatingMenu(ev) {
	//alert()
    if (typeof ev != "undefined") {
		var s = ev.target;
	} else {
		var s = event.srcElement;
    }
	
	// correction positioning of the menu
	var topPosCorrection;
	var xPosCorrection = 0;
	var ver = getInternetExplorerVersion();


	//alert(String(returnDocumentName()).toLowerCase())

    switch (String(returnDocumentName()).toLowerCase()) {
	    case "multi": case "subscription": case "chooseprogram":
	        topPosCorrection = 59;

	        break;

	    default:
	        topPosCorrection = 0;
	        break;
	}

	switch (String(returnDocumentName()).toLowerCase()) {
	    case "index":
	        //alert(ver)
            if (ver > -1) {
	            if (ver >= 8.0) {
	                xPosCorrection = topMenuxPosCorrection;
	                //alert(xPosCorrection)
	            }

	            if (ver == 7) {
	                xPosCorrection = topMenuxPosCorrection + 0;
	                //alert(xPosCorrection)
	            }
	        }

	        break;
        case "registration":
	        //alert(ver)
            if (ver > -1) {
	            if (ver >= 8.0) {
	                xPosCorrection = topMenuxPosCorrection - 4;
	                //alert(xPosCorrection)
	            }

	            if (ver == 7) {
	                xPosCorrection = (topMenuxPosCorrection - 4) + 0;
	                //alert(xPosCorrection)
	            }
	        }

	        break;

	    default:
	        if (ver > -1) {
	            if (ver >= 8.0) {
	                xPosCorrection = topMenuxPosCorrectionDefault;
	                //alert(xPosCorrection)
	            }

	            if (ver == 7) {
	                xPosCorrection = topMenuxPosCorrection + 0;
	                //alert(xPosCorrection)
	            }
	        }
	        break;
	}

	//alert(String(returnDocumentName()).toLowerCase())
	//alert(xPosCorrection)
    

	// Display the menu
	document.getElementById("floater_" + this.id).style.top = (23 + topPosCorrection) + "px";
	document.getElementById("floater_" + this.id).style.left = GetRealX(s) + xPosCorrection + "px";
	document.getElementById("floater_" + this.id).onmouseover = HandleCatchExit;
	document.body.onmousemove = HandleCatchLeaveMenu;
	document.body.floatingMenuItem = document.getElementById("floater_" + this.id);
}

function HandleCatchExit(ev) {
	if (typeof ev != "undefined") {
		var s = ev.target;
	} else {
		var s = event.srcElement;
	}
	this.onmouseover = null;
}
function HandleCatchLeaveMenu(ev) {
	if (typeof ev != "undefined") {
		var s = ev.target;
	} else {
		var s = event.srcElement;
	}
	if (IsPartOfFloat(s) == false) {
		document.body.floatingMenuItem.style.top = "-100px";
		document.body.onmousemove = null;
		document.body.floatingMenuItem = null;
	}
}

function IsPartOfFloat(who) {
//debugger
    if (who.className == "FloatingMenu" || who.className == "BLFloatingMenu" || who.id == document.body.floatingMenuItem.id.split("floater_").join("")) return true;
	var p = who.parentNode;
	while (1==1) {
		if (p == document.body || typeof p.className == "undefined" || typeof who.id == "undefined") return false;
		if (p.className == "FloatingMenu" || p.className == "BLFloatingMenu" || who.id == document.body.floatingMenuItem.id.split("floater_").join("")) return true;
		p = p.parentNode;
	}
	return false;
}
function GetRealY(who) {
    var obj = (typeof who == "string") ? document.getElementById(who) : who;
	var res = 0;
	var t = who;
	while (1 == 1) {
		if (typeof t.offsetTop != "undefined") res += t.offsetTop;
		t = t.offsetParent;
		 if (t == document.body || t == null) {
		     //if (t == null)
		     //   alert("null " + who.id);
		     return res;
		 }
}
}
function GetRealX(who) {
    try {
        var obj = (typeof who == "string") ? document.getElementById(who) : who;
        var res = 0;
        var t = who;
        while (1 == 1) {
            if (typeof t.offsetLeft != "undefined") res += t.offsetLeft;
            t = t.offsetParent;
            if (t == document.body) return res;
        }
    }
    catch (err) { }
}

/* Shader functions */

function ShowShader() {
	// Display shader
	var w = document.body.scrollWidth + "px";
	var h = document.body.scrollHeight + "px";
	var s = document.getElementById("whiteShade");
	// Resize shader
	if (IE == false) {
		var offset = (document.body.scrollWidth - document.body.offsetWidth);
	} else {
		var offset = document.body.scrollLeft;
		if (offset < 0) offset = 0;
	}
	s.style.display = "block";
	s.style.top = "0px";
	s.style.right = "0px";
	s.style.width = w;
	s.style.height = h;
	/*s.style.width = document.body.scrollWidth + "px";
	s.style.height = document.body.scrollHeight + "px";*/
	// Position shader
	/*s.style.top = s.style.left = "0px";*/
	// Hide all selects
	var allSelects = document.getElementsByTagName("select");
	if (allSelects != null) {
		for (var i=0;i<allSelects.length;i++) {
			if (isPartOfMainTable(allSelects[i]) == true && allSelects[i].className.indexOf("SelInvisible")==-1) {
				if (allSelects[i].className.indexOf("SelVisible")==-1) 
					allSelects[i].className += " SelInvisible";
				else
					allSelects[i].className = allSelects[i].className.replace("SelVisible","SelInvisible");
			}
		}
	}
	return s;
}
function HideShader() {
	// Display shader
	var s = document.getElementById("whiteShade");
	// Resize shader
	s.style.width = "1px";
	s.style.height = "1px";
	// Position shader
	s.style.top = "-100px";
	s.style.right = "0px";
	// Reveal all selects
	var allSelects = document.getElementsByTagName("select");
	if (allSelects != null) {
		for (var i=0;i<allSelects.length;i++) {
			if (isPartOfMainTable(allSelects[i]) == true && allSelects[i].className.indexOf("SelInvisible")>-1) {
				allSelects[i].className = allSelects[i].className.replace("SelInvisible","SelVisible");
			}
		}
	}
	window.onresize = null;
}
function isPartOfMainTable(who) {
	var mt = document.getElementById("_mainTable");
	if (who == mt) return true;
	if (who == document.body) return false;
	var temp = who.parentNode;
	while (typeof temp != "undefined" && temp != document.body) {
		if (temp == mt) return true;
		temp = temp.parentNode;
	}
	return false;
}

/* ******************** quick registration popup *********************************************** */
function quick_registration_popup() {		// <---- for uniformity, all function names should have their first letters CAPITAL, and with no _
	var s = ShowShader();			// <---- missing ;!
	curr_popup = "quick_registration";
	// Position the images popup
	var p = document.getElementById("quick_registration");
	var midPointX = Math.round((s.offsetWidth - p.offsetWidth) / 2);
	//var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	var midPointY = document.body.scrollTop + 10;
	//p.style.left = midPointX + "px";
	p.style.right = "0px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	document.getElementById("quick_registrationframe").className = "Hidden";
	document.getElementById("quick_registrationframeoverlay").style.display = "block";
	document.getElementById("quick_registrationframe").src = "/registration_popup.aspx";
	//scroll_interval = setInterval(setPopupY,50);
	window.onresize = ResetQRPopupLocation;
}

function ResetQRPopupLocation() {
	var s = document.getElementById("whiteShade");
	var p = document.getElementById(curr_popup);
	s.style.display = "none";
	//p.style.display = "none";
	// Resize shader
	setTimeout(ResetQRWhite,100);
}
function ResetQRWhite() {
	var w = document.body.scrollWidth;
	if (IE == false) {
		var offset = document.body.scrollWidth - document.body.offsetWidth;
	} else {
		var offset = 0;
	}
	var h = document.body.scrollHeight;
	var s = document.getElementById("whiteShade");
	var p = document.getElementById(curr_popup);
	s.style.display = "block";
	s.style.top = "0px";
	//s.style.left = (0 - offset)+"px";
	s.style.right = "0px";
	if (IE == false) {
		//s.style.left = (0-offset) + "px";
	}
	s.style.width = w+"px";
	s.style.height = h+"px";
	//p.style.display = "block";
	p.style.right = "0px";
}

function GetMainTable() {
	if (document.getElementById("_mainTable")!=null) return document.getElementById("_mainTable");
	var t = document.getElementsByTagName("table");
	if (t!=null) {
		for (var i=0;i<t.length;i++) {
			if (typeof t[i].className != "undefined" && t[i].className.toLowerCase() == "mainTable") {
				return t[i];
			}
		}
	}
	return null;
}

// ******************** Images popup  ************************************************************

function OpenImagesPopup(uid) {
	ShowShader();
	// Position the images popup
	curr_popup = "imagespopup";
	var p = document.getElementById("imagespopup");
	//var midPointX = Math.round((document.body.scrollWidth - p.offsetWidth) / 2);
	var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	//p.style.left = midPointX + "px";
	p.style.right = "0px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	document.getElementById("imagespopupframe").className = "Hidden";
	document.getElementById("imagespopupframeoverlay").style.display = "block";
	document.getElementById("imagespopupframe").src = "/popUserImages.aspx?uid=" + uid;
	scroll_interval = setInterval(setPopupY,50);
	window.onresize = ResetQRPopupLocation;
}

// ******************** homepage pass popup  ************************************************************

function OpenHomepagePassPopup(uid) {
    //alert(ddlSearchAgeFromClientID)
    //ToggleMiniSearchMainDropDowns();
	
	ShowShader();
	// Position the images popup
	curr_popup = "PassPopup";
	var p = document.getElementById("PassPopup");
	//var midPointX = Math.round((document.body.scrollWidth - p.offsetWidth) / 2);
	var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	//p.style.left = midPointX + "px";
	p.style.right = "0px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	document.getElementById("PassPopupframe").className = "Hidden";
	document.getElementById("PassPopupframeoverlay").style.display = "block";
	document.getElementById("PassPopupframe").src = "/homepage_pass_popup.aspx";
	scroll_interval = setInterval(setPopupY,50);
	window.onresize = ResetQRPopupLocation;
}

function ClosePopup3(popup) {
    try {
        //alert(3)
        HideShader();
        clearInterval(scroll_interval)
        var p = document.getElementById(popup);
        p.style.top = "-1000px";
        if (document.getElementById("hlist") != null) document.getElementById("hlist").style.display = "block";
        if (document.getElementById("hsent") != null) document.getElementById("hsent").style.display = "none";
        window.onresize = null;
    }
    catch (err) { }
}

function ClosePopup2() {
    var p = document.getElementById(curr_popup);
    if (curr_popup == "badLogin" || curr_popup == "badLogin2") {
        ClosePopup3("badLogin");
        ClosePopup3("badLogin2");
    }
    else
        ClosePopup3(curr_popup);
}


// ******************** general popup functions ************************************************************

function Event_PopupLoaded(popup) {
	document.getElementById(curr_popup+"frameoverlay").style.display = "none";
	document.getElementById(curr_popup+"frame").className = "Visible";
}
function ClosePopup() {

    if (document.location.href.indexOf('main.aspx') > -1)
        ToggleMiniSearchMainDropDowns();
	
	HideShader();
	clearInterval(scroll_interval)
	var p = document.getElementById(curr_popup);
	p.style.top = "-1000px";
	document.getElementById(curr_popup+"frame").className = "Hidden";
	document.getElementById(curr_popup+"frameoverlay").style.display = "block";
	window.onresize = null;
}

function ToggleMiniSearchMainDropDowns() {
    if (typeof (ddlSearchAgeFromClientID) != 'undefined') {
        var ddlSearchAgeFrom = document.getElementById(ddlSearchAgeFromClientID);
        var ddlSearchRegions = document.getElementById(ddlSearchRegionsClientID);
        var ddlSearchAgeTo = document.getElementById(ddlSearchAgeToClientID);
        //debugger
        if (ddlSearchAgeFrom) {
            if (ddlSearchAgeFrom.style.visibility == 'visible' || ddlSearchAgeFrom.style.visibility == '') {
                ddlSearchAgeFrom.style.visibility = 'hidden';
                ddlSearchRegions.style.visibility = 'hidden';
                ddlSearchAgeTo.style.visibility = 'hidden';
            }
            else {
                ddlSearchAgeFrom.style.visibility = 'visible';
                ddlSearchRegions.style.visibility = 'visible';
                ddlSearchAgeTo.style.visibility = 'visible';
            }
        }
    }
}

/******************* Bad login popup *********************/
function OpenBadLoginPopup() {
	ShowShader();
	// Position the images popup
	curr_popup = "badLogin";
	var p = document.getElementById("badLogin");
	var midPointX = Math.round((document.body.scrollWidth - p.offsetWidth) / 2);
	var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	p.style.left = midPointX + "px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	scroll_interval = setInterval(setPopupY,50);
}

function OpenInactiveLoginPopup() {
	ShowShader();
	// Position the images popup
	curr_popup = "badLogin2";
	var p = document.getElementById("badLogin2");
	var midPointX = Math.round((document.body.scrollWidth - p.offsetWidth) / 2);
	var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	p.style.left = midPointX + "px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	scroll_interval = setInterval(setPopupY,50);
}

function OpenBadRangePopup() {
	ShowShader();
	// Position the images popup
	curr_popup = "badAgeRange";
	var p = document.getElementById("badAgeRange");
	var midPointX = Math.round((document.body.scrollWidth - p.offsetWidth) / 2);
	var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	p.style.left = midPointX + "px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	scroll_interval = setInterval(setPopupY,50);
}

function OpenBadSMSPopup() {
	ShowShader();
	// Position the images popup
	curr_popup = "badSMSTime";
	var p = document.getElementById("badSMSTime");
	var midPointX = Math.round((document.body.scrollWidth - p.offsetWidth) / 2);
	var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	p.style.left = midPointX + "px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	scroll_interval = setInterval(setPopupY,50);
}
function OpenBadPhonePopup() {
	ShowShader();
	// Position the images popup
	curr_popup = "badPhone";
	var p = document.getElementById("badPhone");
	var midPointX = Math.round((document.body.scrollWidth - p.offsetWidth) / 2);
	var midPointY = Math.round((document.body.offsetHeight - p.offsetHeight) / 2) + document.body.scrollTop;
	p.style.left = midPointX + "px";
	if (midPointY<0) {
		midPointY = 10;
	}
	p.style.top = midPointY + "px";
	scroll_interval = setInterval(setPopupY,50);
}
/* Login state ping */

var LoginAjax = null;
var LoginAjaxInProgress = false;
var LoginAjaxTimeout = null;
function initLoginAjax() {
	try {
		// Firefox, Opera 8.0+, Safari
		LoginAjax = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			LoginAjax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				LoginAjax = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				//alert("Your browser does not support AJAX!");
				LoginAjax = null;
			}
		}
	}
}

function RequestLoginAjax() {
    //alert('RequestLoginAjax')
	if (LoginAjaxInProgress == true) {
	    LoginAjaxTimeout = setTimeout(RequestLoginAjax, 10000);
		return;
	}
	initLoginAjax();
	LoginAjax.onreadystatechange = LoginAjaxCallback;
	//LoginAjax.open("GET","/inc/counters.aspx",true);
	LoginAjax.open("GET","/inc/counters.ashx",true);
	LoginAjax.send(null);
	LoginAjaxInProgress = true;
	LoginAjaxTimeout = -1;
}

function LoginAjaxCallback() {
	if (LoginAjax.readyState == 4) {
		LoginAjaxInProgress = false;
		if (LoginAjax.responseText.toLowerCase() == "logout") {
			document.location.href = "/logout.aspx";
			return;
		}
		var Results = LoginAjax.responseText.toString();
		if (Results.indexOf("~!~") == -1) return;
		Results = Results.split("~!~");
		if (Results.length < 2) return;
		for (var i=0;i<Results.length;i++) {
			var p = document.getElementById("ping"+i);
			if (p != null && typeof Results[i] != "undefined") {
				if (Results[i].toString() != "") p.innerHTML = Results[i].toString();
				if (i==0) {
					var line = document.getElementById("line0");
					if (line != null) {
						line.className = (Results[i].toString() == "0")?"LinkedItem ItemMail":"LinkedItem ItemMail MarkedItem";
					}
				}
			}
		}
		LoginAjaxTimeout = setTimeout(RequestLoginAjax, 15000);
	}
}

/* Cellular ajax */

var CellAjax = null;
var CellAjaxInProgress = false;
var CellAjaxPrefix = "";
function initCellAjax() {
	try {
		// Firefox, Opera 8.0+, Safari
		CellAjax = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			CellAjax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				CellAjax = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				CellAjax = null;
				return false;
			}
		}
	}
}

function RequestCellAjax(ucid) {
	if (CellAjaxInProgress == true) {
		return;
	}
	var phoneNumber = document.getElementById("ddlPrefix").value + document.getElementById("txtNumber").value;
	var regPhone = /^[2-9]\d{6}/;
	if (regPhone.test(document.getElementById("txtNumber").value.toString()) == false) {
		OpenBadPhonePopup();
		return;
	}
	initCellAjax();
	CellAjaxPrefix = ucid;
	CellAjax.onreadystatechange = CellAjaxCallback;
	CellAjax.open("GET","/inc/cellular_send.aspx?itm=" + phoneNumber,true);
	CellAjax.send(null);
	CellAjaxInProgress = true;
}

function CellAjaxCallback() {
	if (CellAjax.readyState == 4) {
		CellAjaxInProgress = false;
		var Results = CellAjax.responseText;
		if (Results == "1") {
			document.getElementById("senderBlock").style.display = "none";
			document.getElementById("errorBlock").style.display = "none";
			document.getElementById("timeoutBlock").style.display = "none";
			document.getElementById("thankyouBlock").style.display = "block";
			window.setTimeout(ShowCellAjaxAgain,30000);
		} else if (Results == "2") {
			document.getElementById("senderBlock").style.display = "none";
			document.getElementById("errorBlock").style.display = "none";
			document.getElementById("thankyouBlock").style.display = "none";
			document.getElementById("timeoutBlock").style.display = "block";
			window.setTimeout(ShowCellAjaxAgain,30000);
		} else {
			document.getElementById("senderBlock").style.display = "none";
			document.getElementById("thankyouBlock").style.display = "none";
			document.getElementById("timeoutBlock").style.display = "none";
			document.getElementById("errorBlock").style.display = "block";
			window.setTimeout(ShowCellAjaxAgain,30000);
		}
	}
}

function ShowCellAjaxAgain() {
	document.getElementById("errorBlock").style.display = "none";
	document.getElementById("thankyouBlock").style.display = "none";
	document.getElementById("timeoutBlock").style.display = "none";
	document.getElementById("senderBlock").style.display = "block";
	document.getElementById("txtNumber").value = "";
}

String.prototype.Replace = function(what,by) {
	return this.split(what).join(by);
}
String.prototype.ReplaceMulti = function(what, by) {
	var temp = this;
	for (var i=0;i<what.length;i++) {
		temp = temp.split(what[i]).join(by);
	}
	return temp;
}

String.prototype.NumbersOnly = function() {
	var temp = "";
	for (var i=0;i<this.length;i++) {
		if (this.charAt(i) == "0" || this.charAt(i) == "1" || this.charAt(i) == "2" || this.charAt(i) == "3" || this.charAt(i) == "4" || 
			this.charAt(i) == "5" || this.charAt(i) == "6" || this.charAt(i) == "7" || this.charAt(i) == "8" || this.charAt(i) == "9") {
			temp += this.charAt(i);
		}
	}
	return temp;
}

String.prototype.TrimSpaces = function() {
	var temp = this;
	if (temp == "" || (temp.length >= 2 && temp.charAt(0) != " " && temp.charAt(temp.length-1) != " ")) return temp;
	while (temp.length > 0 && temp.charAt(0) == " ") {
		temp = temp.substr(1);
	}
	while (temp.length > 0 && temp.charAt(temp.length-1) == " ") {
		temp = temp.substr(0,temp.length-1);
	}
	return temp;
}

/* Tabs */

function CustomTabClick(who,optReset) {
    // Check if on homepage
    //alert(document.location.href.toLowerCase().indexOf("index.aspx"))
    //alert('CustomTabClick')
	if (document.location.href.toLowerCase().indexOf("index.aspx")>-1) {
		// Check if custom tab is already present
		
		if (CustomTabObj == null) {
			CustomTabObj = document.createElement("div");
			CustomTabObj.className = "TabCustNorm";
			document.getElementById("tabContainer").appendChild(CustomTabObj);
		}
		// Fill
		CustomTabObj.innerHTML = "<div><a href=\"javascript:DoNothing();\" id=\"alnkTab5\" tabid=\""+who.getAttribute("tabid")+"\" onclick=\"TabClick(this,"+who.getAttribute("tabid")+");\">"+who.innerHTML+"</a></div>";
		// Simulate click
		TabClick(document.getElementById("alnkTab5"),who.getAttribute("tabid"),optReset);
	}
}

function DoNothing() {
}

var bubble_txt = "";
var curr_obj_orgClass;
var curr_obj;
var bubbleInt = null;
var bubbleOpener = null;

function bubble_func(obj) {
    //alert()
    //debugger
  
	if (obj.style.border != "") {
		try { delete obj.style.border; } catch(e) {
			try { obj.style.border = null; } catch(e) { obj.style.border = "1px solid #9C9C9C"; }
		}
	}
	curr_obj_orgClass = obj.className;
	curr_obj = obj;
	var e = document.getElementById("errorBubble");
	if (e != null && e.caller == obj) return; else if (e != null && e.caller != obj) {
		e.style.top = "-1000px";
		e.caller = null;
	}
	//curr_obj_orgClass = obj.getAttribute("class");
	if (obj.getAttribute("type") == "text" || obj.getAttribute("type") == "password") {
		//obj.setAttribute("class","unselected_"+obj.getAttribute("class"));
		if (obj.className.indexOf("unselected") == -1)
		    obj.className = "unselected_"+obj.className;
	}
	if (obj.tagName.toLowerCase() == "textarea") obj.className = "texterea_selected";
	if (obj.getAttribute("bubbleText") != null && obj.getAttribute("bubbleText") != ""){
		bubble_txt = obj.getAttribute("bubbleText");
		var k = document.getElementById("bubble");
		var T = document.getElementById("bubble_content");
		T.innerHTML = bubble_txt;
		var tp = GetRealY(obj);
		var explicitAddon = obj.getAttribute("BubbleOffset");
		if (window.navigator.appName.toLowerCase().indexOf("explorer") > -1) {
			if (explicitAddon != null) {
				var addon = parseInt(explicitAddon) - 10;
			} else {
				var addon = -10; 
			}
			var vaddon = 0;
		} else {
			if (explicitAddon != null) {
				var addon = parseInt(explicitAddon) + 20;
			} else {
				var addon = 20;
			}
			var vaddon = -20;
		}
		tp = tp - Math.round((k.offsetHeight - obj.offsetHeight) / 2);
		
		k.style.top = (tp + vaddon) + "px";
		k.style.left = (GetRealX(document.getElementById("rt")) + addon) + "px";
	} else {
		var k = document.getElementById("bubble");
		k.style.top = -5000 + "px";
		k.style.left = 10 + "px";		
	}	
}

function close_bubble(optCaller, optClearErrorOnly) {
    //debugger
    
	if (typeof optCaller != "undefined" && optCaller != null && optCaller.style.border != "") {
		try { delete optCaller.style.border; } catch(e) {
			try { optCaller.style.border = null; } catch(e) { optCaller.style.border = "1px solid #9C9C9C"; }
		}
	}
	if (typeof optCaller != "undefined" && optCaller != null && optCaller.style.color != "") {
		try { optCaller.style.color = "#000000"; } catch(e) {}
	}
	if (optClearErrorOnly == true) return;
	if (typeof curr_obj != "undefined" && curr_obj != null) {
		curr_obj.className = curr_obj_orgClass;
		var k = document.getElementById("bubble");
		k.style.top = -5000 + "px";
	}
	var e = document.getElementById("errorBubble");
	if (e != null) {
		if (e.caller == curr_obj) {
			e.style.top = "-1000px";
			e.caller = null;
		}
	}
	if (optCaller && (optCaller.id == "txtNewPassword" || optCaller.id == "txtNewPasswordVerify")) {
		if (document.getElementById("txtNewPassword").value != document.getElementById("txtNewPasswordVerify").value && document.getElementById("txtNewPassword").value != "" && document.getElementById("txtNewPasswordVerify").value != "") {
			setTimeout('ShowErrorBubble(document.getElementById("txtNewPassword"),hebtxt18,"no");',100);
		}
	}
	if (optCaller && (optCaller.id == "txtPassword" || optCaller.id == "txtPasswordVerify")) {
		if (document.getElementById("txtPassword").value != document.getElementById("txtPasswordVerify").value && document.getElementById("txtPassword").value != "" && document.getElementById("txtPasswordVerify").value != "") {
			setTimeout('ShowErrorBubble(document.getElementById("txtPassword"),hebtxt18,"no");',100);
		}
	}

	if (optCaller && (optCaller.id == "txtEmail" || optCaller.id == "txtEmailVerify"))
	{
	    if (document.getElementById("txtEmailVerify"))
	        if (document.getElementById("txtEmail").value != document.getElementById("txtEmailVerify").value && document.getElementById("txtEmail").value != "" && document.getElementById("txtEmailVerify").value != "") {
	        setTimeout('ShowErrorBubble(document.getElementById("txtEmail"),hebtxt20,"no");', 100);
	    }
	}
}

function PositionBubble() {
	var k = document.getElementById("bubble");
	k.style.top = (GetRealY(bubbleOpener)-40) + "px";
	k.style.left = (GetRealX(document.getElementById("tabContainer").parentNode)+20) + "px";
}

function ShowErrorBubble(who, message, optDoScroll, optXCorr, optYCorr, hide) {
	if (who == null) return;
	close_bubble();
	var k = document.getElementById("errorBubble");
	if (k == null) return;
	k.caller = who;
	var tp = GetRealY(who);
	var of = k.getAttribute("offsetFromLeft");
	if (who.getAttribute("errorOffsetFromLeft") != null) {
		// Definition on caller takes precedence
		of = parseInt(who.getAttribute("errorOffsetFromLeft"));
}
if (of == null) var offs = 0; else var offs = parseInt(of);
	if (window.navigator.appName.toLowerCase().indexOf("explorer")>-1) {
		var vaddon = 5;
	} else {
		var vaddon = 5;
	}
	var ov = k.getAttribute("offsetFromTop");
	if (ov != null) ov = parseInt(ov);
	if (isNaN(ov) == true) ov = 0;
	tp = tp - Math.round((k.offsetHeight - who.offsetHeight) / 2);
	if (typeof optXCorr != "undefined" && !isNaN(optXCorr) && optXCorr != null) var ox = optXCorr; else var ox = 0;
	if (typeof optYCorr != "undefined" && !isNaN(optYCorr) && optYCorr != null) var oy = optYCorr; else var oy = 0;
	k.style.top = (tp + vaddon + ov + oy) + "px";
	var scrollY = tp + vaddon + ov + oy;
	k.style.left = (GetRealX(document.getElementById("rt")) + offs + ox) + "px";
	document.getElementById("_errCont").innerHTML = "<div><img src='../img/red_exclamation.PNG' />" + message + "</div>";
	//if (optDoScroll != "no") document.body.scrollTop = (GetRealY(who) - 100);
	if (optDoScroll != "no") document.body.scrollTop = (0);
	document.onmousedown = HideErrorBubble;
	window.scrollTo(0, scrollY-100);
}

function HideErrorBubble() {
	var e = document.getElementById("errorBubble");
	if (e != null) {
		e.style.top = "-1000px";
		e.caller = null;
		document.onmousedown = null;
	}
}

/* Chat handlers */
function UpdateWindowRef(name, winref, optIsInitiator) {
	ChatWindows[name+""] = winref;
	if (typeof optIsInitiator != "undefined" && optIsInitiator == true) {
		InitiatedWindows[name + ""] = winref;
	}
}

function WindowWasClosed(name) {
	RequestIMCloseAjax(name);
	for (var i in ChatWindows) {
		if (i.toString() == name.toString()) {
			ChatWindows[name] = null;
			break;
		}
	}
	for (var i in InitiatedWindows) {
		if (i.toString() == name.toString()) {
			Con("Removed " + name + " from initiated");
			InitiatedWindows[name] = null;
			return;
		}
	}
}

var WinMaintain = null;
function WindowMaintenance() {
	for (var k in ChatWindows) {
		if (k != "Filp" && ChatWindows[k] != null && typeof ChatWindows[k].closed != "undefined" && ChatWindows[k].closed == true) {
			RequestIMCloseAjax(k.toString());
			for (var i in InitiatedWindows) {
				if (i == k) {
					InitiatedWindows[i] = null;
					break;
				}
			}
			ChatWindows[k] = null;
		}
	}
}

function IsWindowOpen(name) {
	for (var i in ChatWindows) {
		if (i.toString() == name.toString()) {
			if (ChatWindows[i] != null && typeof ChatWindows[i].closed != true) {
				return ChatWindows[i];
			} else {
				return null;
			}
		}
	}
	return null;
}
function CountInitiatedWindows() {
	var tot = 0;
	for (var i in InitiatedWindows) {
		if (InitiatedWindows[i] != null && typeof InitiatedWindows[i] != "undefined" && i != "Flip" && i != "flip") {
			tot++;
		}
	}
	Con("Counted " + tot + " initiated windows");
	return tot;
}

function SafeWindowName(original) {
	var ret = original.toString();
	var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
	//*%#$\-\ 
	ret = ret.Replace("*","_ykm_");
	ret = ret.Replace("%","_ykm_");
	ret = ret.Replace("#","_ykm_");
	ret = ret.Replace("$","_ykm_");
	ret = ret.Replace("-","_ykm_");
	ret = ret.Replace(" ","_ykm_");
	var temp = "";
	for (var i = 0; i<ret.length; i++) {
		var thisnum = ret.charCodeAt(i);
		while (thisnum > 0) {
			var leftover = thisnum % valid.length;
			temp = temp + valid.charAt(leftover);
			thisnum -= leftover;
			thisnum = thisnum / valid.length;
		}
	}
	return temp;
}

function EngageChatWith(who, didNotEngage) {
	if (didNotEngage != true) {
		var special = "";
	} else {
		var special = "&ignoreinit=1";
	}
	var cm = document.getElementById((IE==true)?"chatmanager":"chatmanagermz");
	
	var wopen = (cm)? (cm.IsWindowOpen(who) || cm.IsWindowOpen(who)) : false;
	
	if (wopen == false) {
		//setTimeout(DelayedOpenChatWindow,250,who,special,SafeWindowName(who));
		window.open("Chat.aspx?uname=" + escape(who) + special,"chatwindow_"+SafeWindowName(who),"width=476,height=426,scrollbars=no,toolbars=no");
	}
}

function Out(msg) {
	//document.title = msg;
}
/* SetTab */

var STAjax = null;
function ResetTab(tabid) {
	try { STAjax = new XMLHttpRequest(); } catch (e) {
		try { STAjax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
			try { STAjax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
				STAjax = null;
			}
		}
	}
	if (STAjax != null) {
		STAjax.onreadystatechange = Redirector;
		STAjax.open("GET","/inc/setTab.ashx?tabid="+tabid,true);
		STAjax.send(null);
	}
}
function Redirector() {
	if (STAjax.readyState == 4) {
	    //document.location.href = document.location.href.substr(0,document.location.href.substr(7).indexOf("/") + 7);
	    try
	    {
		if (httplink != null)
		    document.location.href = httplink + "index.aspx";
		 }
		 catch(Ex){
		    document.location.href = "/index.aspx";
		 }
	}
}

/* SetMailboxPage */

var SMAjax = null;
function ResetMailboxPage(rfid) {

	try { SMAjax = new XMLHttpRequest(); } catch (e) {
		try { SMAjax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
			try { SMAjax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
				SMAjax = null;
			}
		}
	}
	if (SMAjax != null) {
		SMAjax.onreadystatechange = MBRedirector;
		SMAjax.open("GET","/inc/setMailPage.ashx?rfr="+rfid,true);
		SMAjax.send(null);
	}
}
function MBRedirector() {
	if (SMAjax.readyState == 4) {
		if (SMAjax.responseText != "1" && SMAjax.responseText != "2") var redir = "1"; else var redir = SMAjax.responseText;
		document.location.href = httplink1 + "mailbox.aspx?rfid="+redir;
	}
}

/* Ajax */
var IMPing = null;
var IMAjax = null;
var IMCancelAjax = null;
var IMCloseAjax = new Array();
var IMAjaxInProgress = false;

function initIMAjax(mode) {
	//alert()
	if (mode == "im") {
		try { IMAjax = new XMLHttpRequest(); } catch (e) {
			try { IMAjax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
				try { IMAjax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
					IMAjax = null;
				}
			}
		}
	} else if (mode == "cancel") {
		try { IMCancelAjax = new XMLHttpRequest(); } catch (e) {
			try { IMCancelAjax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
				try { IMCancelAjax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
					IMCancelAjax = null;
				}
			}
		}
	} else if (mode == "close") {
		try { var temp = new XMLHttpRequest(); } catch (e) {
			try { var temp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
				try { var temp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
					var temp = null;
				}
			}
		}
		IMCloseAjax.push(temp);
		return temp;
    } else if (mode == "send") {
                try { var tempsend = new XMLHttpRequest(); } catch (e) {
                    try { var tempsend = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
                        try { var tempsend = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
                            var tempsend = null;
                }
            }
        }
        //IMCloseAjax.push(temp);
        return tempsend;
    }
}

function RequestIMAjax() {
	//alert(2)
	if (IMAjaxInProgress == true) {
		IMPing = setTimeout(RequestIMAjax,7000);
		return;
	}
	initIMAjax("im");
	if (IMAjax == null) {
		IMPing = setTimeout(RequestIMAjax,7000);
		return;
	}
	if (WinMaintain == null) {
		WinMaintain = setInterval(WindowMaintenance,50);
	}
	IMAjax.onreadystatechange = IMAjaxCallback;
	//IMAjax.open("POST","/inc/InstantMessaging.aspx",true);
	IMAjax.open("POST","/inc/InstantMessaging.ashx",true);
	IMAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	// Build POST string
	var postData = "Action=Get";
	try {
		IMAjax.send(postData);
	} catch(e) {
	}
	IMAjaxInProgress = true;
}

function RequestIMCancelAjax(username) {
	var aj = initIMAjax("close");
	if (aj == null) return;
	aj.onreadystatechange = IMCloseAjaxCallback;
	//aj.open("POST","/inc/InstantMessaging.aspx",true);
	aj.open("POST","/inc/InstantMessaging.ashx",true);
	aj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	// Build POST string
	var postData = "Action=Clear&User="+username;
	aj.send(postData);
}

function RequestIMCloseAjax(username) {
	var aj = initIMAjax("close");
	if (aj == null) return;
	aj.onreadystatechange = IMCloseAjaxCallback;
	//aj.open("POST","/inc/InstantMessaging.aspx",true);
	aj.open("POST","/inc/InstantMessaging.ashx",true);
	aj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
	// Build POST string
	var postData = "Action=Close&User="+username;
	aj.send(postData);
}

function IMCloseAjaxCallback() {
	for (var i=0;i<IMCloseAjax.length;i++) {
		if (typeof IMCloseAjax[i].readyState != "undefined") {
			if (IMCloseAjax[i].readyState == 4) {
				IMCloseAjax[i] = null;
			}
		} else {
			IMCloseAjax[i] = null;
		}
	}
	while (1==1) {
		var nochange = true;
		for (var i=0;i<IMCloseAjax.length;i++) {
			if (IMCloseAjax[i] == null) {
				IMCloseAjax.splice(i,1);
				nochange = false;
				break;
			}
		}
		if (nochange == true) return;
	}
}


function RequestIMSendAjax(username) {
    var aj = initIMAjax("send");
    if (aj == null) return;
    ///aj.onreadystatechange = IMCloseAjaxCallback;
    //aj.open("POST","/inc/InstantMessaging.aspx",true);
    aj.open("POST", "/inc/InstantMessaging.ashx", true);
    aj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    // Build POST string
    var msgBody = TrimSpaces(FilterInput(ClearLinebreaks('editorBody.valu_test14e' + '<input type=hidden value=\'' + username + '#\' />')));
    var postData = "Action=Send&User=" + username + "&Message=" + msgBody;
    aj.send(postData);
}

///chat alert - this is the one used
///thisUser - the sender
function CreateAlerter(thisUser, showmessage) {
    //alert('CreateAlerter')
    //return;
	//debugger 
	if (IE == true) {
	    var cm = document.getElementById("chatmanager");
	}
	else {
	    var cm = document.getElementById("chatmanagermz");
	}
     
    var recipientUserName = showmessage.substring(showmessage.indexOf('value') + 7, showmessage.indexOf('#'));
    //alert(showmessage)
    //alert(recipientUserName);
    //alert(CurrentUserName);

    if (recipientUserName != '' && recipientUserName.length > 0 && (recipientUserName.toLowerCase() != CurrentUserName.toLowerCase()))
    {
        cm.CancelChat(thisUser);
        return;
    }
    
    //alert(1);
	if (document.getElementById("Alerter"+SafeWindowName(thisUser)) == null) {
	    
	    // No open window, create alerter
	    var d = document.createElement("div");
	    d.id = 'userMessageAlertHolder';
	    d.targetUser = thisUser.toString();

	    var strBeginChatSessionLink = 'BeginChatSession(this);';

	    var lnk = "javascript:void(0)";
	    var InputHtml='';
	    
	    if ((!IsSubScriber && !IsDelegatedSubScriber) && IsOnline) {
	        strBeginChatSessionLink = 'DoNothing();';
	        lnk = httpslink + 'secure/subscription.aspx?rs=1';
	        InputHtml='רוצים לענות לפונה?<br /><a href="' + lnk + '">לחצו כאן</a> לרכישת מנוי';
	    }
	    else{
	          InputHtml ='<a href="' + lnk + '" onclick="' + strBeginChatSessionLink + '">' + showmessage.Replace("[[amp]]", "&").Replace("[[dq]]", "\"").Replace("=&onLoad=[type Function]", "").Replace("&onLoad=[type Function]", "") + '</a>';
	    }
	
	    d.innerHTML = '<div class="userMessageAlert" id="userMessageAlert' + SafeWindowName(thisUser) + '">' +
                            '<div class="umOuterBorder">' +
                                '<div class="umAlertBody">' +
                                    '<div class="umAlertTitle">' + thisUser.toString() + ' פנה אליך!</div>'+InputHtml+                         
	                                '<div class="umClose" onClick="CancelChatSession(this);"><a href="javascript:void(0)" >סגור</a></div>' + //onClick="CloseUserAlert(\'userMessageAlert' + SafeWindowName(thisUser) + '\');"
	                               '</div>' +
                            '</div>' +
                        '</div>';
	    
//	    d.className = "ChatAlert";
//	    d.targetUser = thisUser.toString();
//	    d.id = "Alerter" + SafeWindowName(thisUser);
//	    var dh = document.createElement("div");
//	    dh.className = "Header";
//	    dh.innerHTML = thisUser.toString();
//	    d.appendChild(dh);
//	    var dt = document.createElement("div");
//	    dt.className = "Text";
//	    dt.innerHTML = showmessage.Replace("[[amp]]", "&").Replace("[[dq]]", "\"").Replace("=&onLoad=[type Function]", "").Replace("&onLoad=[type Function]", "");
//	    dt.onclick = BeginChatSession;
//	    d.appendChild(dt);
//	    var dc = document.createElement("div");
//	    dc.className = "Cancel";
//	    dc.innerHTML = "gggg"; //hebtxt21;
//	    dc.onclick = CancelChatSession;
//	    d.appendChild(dc);

	    var alreadyExists = false;
	    
	    for (var i = 0; i < WaitingChats.length; i++) {
	        if (WaitingChats[i].targetUser == d.targetUser && WaitingChats[i].innerHTML == d.innerHTML) {
	            alreadyExists = true;
	        }
	    }
	    
	    if (!alreadyExists) {
	        document.getElementById("chatAlertContainer").appendChild(d);
	        // Add to alerter queue
	        d.currentTop = -300;
	        d.targetTop = 0;
	    
	        WaitingChats.push(d);
	    }

//		// No open window, create alerter
//		var d = document.createElement("div");
//		d.className = "ChatAlert";
//		d.targetUser = thisUser.toString();
//		d.id = "Alerter"+SafeWindowName(thisUser);
//		var dh = document.createElement("div");
//		dh.className = "Header";
//		dh.innerHTML = thisUser.toString();
//		d.appendChild(dh);
//		var dt = document.createElement("div");
//		dt.className = "Text";
//		dt.innerHTML = showmessage.Replace("[[amp]]","&").Replace("[[dq]]","\"").Replace("=&onLoad=[type Function]","").Replace("&onLoad=[type Function]","");
//		dt.onclick = BeginChatSession;
//		d.appendChild(dt);
//		var dc = document.createElement("div");
//		dc.className = "Cancel";
//		dc.innerHTML = "gggg"; //hebtxt21;
//		dc.onclick = CancelChatSession;
//		d.appendChild(dc);
//		document.getElementById("chatAlertContainer").appendChild(d);
//		// Add to alerter queue
//		d.currentTop = -300;
//		d.targetTop = 0;
//		WaitingChats.push(d);
	}
}

String.prototype.Replace = function(what,bywhat) {
	return this.split(what).join(bywhat);
}

function IMAjaxCallback() {
    alert(3)
    //return;
    if (IMAjax.readyState == 4) {
        //debugger;
		IMAjaxInProgress = false;
		var Results = IMAjax.responseText;
		Con(Results);
		if (typeof Results == "undefined" || Results == null || Results == "" || Results == "0" || Results.indexOf("~!~") == -1) {
			// Remove all waiting screens
			for (var z=0;z<WaitingChats.length;z++) {
				document.getElementById("chatAlertContainer").removeChild(WaitingChats[z]);
				WaitingChats.splice(z,1);
				z--;
			}

} else {
//debugger;
			var users = Results.split("~*~");
			var gotUsers = new Array();
			for (var i=0;i<users.length;i++) {
				var userData = users[i].split("~!~");
				var thisUser = userData[0];
				var w = IsWindowOpen(SafeWindowName(thisUser));
				if (w == null) {
					if (document.getElementById("Alerter"+SafeWindowName(thisUser)) == null && typeof userData[1] != "undefined") {
						gotUsers.push(thisUser);
						// No open window, create alerter
						var d = document.createElement("div");
						d.className = "ChatAlert";
						d.targetUser = thisUser.toString();
						d.id = "Alerter"+SafeWindowName(thisUser);
						var dh = document.createElement("div");
						dh.className = "Header";
						dh.innerHTML = thisUser.toString();
						d.appendChild(dh);
						var dt = document.createElement("div");
						dt.className = "Text";
						dt.innerHTML = userData[1].split("~$~")[1];
						dt.onclick = BeginChatSession;
						d.appendChild(dt);
						var dc = document.createElement("div");
						dc.className = "Cancel";
						dc.innerHTML = "[x] בטל";
						dc.onclick = CancelChatSession;
						d.appendChild(dc);
						document.getElementById("chatAlertContainer").appendChild(d);
						// Add to alerter queue
						d.currentTop = -300;
						d.targetTop = 0;
						WaitingChats.push(d);
					} else if (document.getElementById("Alerter"+SafeWindowName(thisUser)) != null && (typeof userData[1] == "undefined" || userData[1] == "")) {
						var wc = document.getElementById("Alerter"+SafeWindowName(thisUser));
						for (var z=0;z<WaitingChats.length;z++) {
							if (WaitingChats[z].targetUser == thisUser) {
								document.getElementById("chatAlertContainer").removeChild(WaitingChats[z]);
								WaitingChats.splice(z,1);
								break;
							}
						}
					}
				} else {
					for (var m=1;m<userData.length;m++) {
						if (typeof w.AcceptMessage != "undefined") {
							w.AcceptMessage(userData[m]);
						}
					}
				}
			}
		}
		IMPing = setTimeout(RequestIMAjax,7000);
	}
}

function Con(msg) {
	if (typeof console != "undefined") {
		console.log(msg);
	}
}

function BeginChatSession(ev) {
    //alert(6);
    EngageChatWith(ev.parentNode.parentNode.parentNode.parentNode.targetUser, true);
	for (var i=0; i < WaitingChats.length ;i++) {
	    if (ev.parentNode.parentNode.parentNode.parentNode == WaitingChats[i]) {
			WaitingChats.splice(i,1);
		}
	}
	document.getElementById("chatAlertContainer").removeChild(ev.parentNode.parentNode.parentNode.parentNode);
}

function CancelChatSession(ev) {
	if (IE == true) var cm = document.getElementById("chatmanager"); else var cm = document.getElementById("chatmanagermz");
	cm.CancelChat(ev.parentNode.parentNode.parentNode.parentNode.targetUser);
	for (var i=0;i<WaitingChats.length;i++) {
	    if (ev.parentNode.parentNode.parentNode.parentNode == WaitingChats[i]) {
			WaitingChats.splice(i,1);
		}
	}
	document.getElementById("chatAlertContainer").removeChild(ev.parentNode.parentNode.parentNode.parentNode);
}

var WaitingChats = new Array();
var WaitingAnim = null;

function AnimateWaiters() {
    //alert(5);
	var nextTop = document.body.scrollTop;
	for (var i=0;i<WaitingChats.length;i++) {
		// Calc proper position
		var wc = WaitingChats[i];
		if (typeof wc != "undefined" && wc != null) {
			wc.targetTop = nextTop;
			nextTop += wc.offsetHeight;
		}
		// Animate
		var diff = wc.targetTop - wc.currentTop;
		if (Math.abs(diff)<0.5) {
			wc.currentTop = wc.targetTop;
		} else {
			wc.currentTop += (diff / 3);
		}
		wc.style.top = (Math.round(wc.currentTop) + "px");
	}
}

function CheckCellError() {
	if (typeof cellError != "undefined" && cellError != null && cellError == true) {
		OpenBadSMSPopup();
	}
}


function CloseUserAlert(id) {
    var ualert = document.getElementById(id);
    ualert.style.display = "none";
}

function UserCardImg_OnError(imgObj, bIsmale) {
    //alert(obj)
    if (imgObj) {
        if (bIsmale.toLowerCase() == 'true')
            imgObj.src = '/img/imgAvatar/Avatar5.jpg';
        else
            imgObj.src = '/img/imgAvatar/Avatar25.jpg';
    }
}

//function addLoadEvent(func) {
//    var oldonload = window.onload;
//    if (typeof window.onload != 'function') {
//        window.onload = func;
//    } else {
//        window.onload = function() {
//            if (oldonload) {
//                oldonload();
//            }
//            func();
//        }
//    }
//}

//addLoadEvent(function() {
//                RegisterElementForFloatingMenu('ucSiteNav_menu2');
//	            RegisterElementForFloatingMenu('ucSiteNav_menu6');
//            });


