﻿var LoginExtenderID;
var RegisterExtenderID;
var AlertExtenderID;
var AddCommentID;
var SendMessageID;
var SendMessageHiddenID;
var SendMessageReplyToID;
var SendMessageSubjectID;
var SendMessageTextID;
var AddDiscussionID;
var AlertMessageID;
var RegisterExtenderID;
var COstatus;
var tbLoginHiddenID;
var tbRegisterHiddenID;
var tbRegisterCloseHiddenID;
var CogScoreExtenderID;

function _void(){
    void 3;
}

function emptyBrowserSelection()
{
    if (document.selection) document.selection.empty();
    else if (window.getSelection) window.getSelection().removeAllRanges();
}

function GetTargetElement(e)
{
    var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
    return targ;
}

/****************************************************************
 ** Assign this as the event handler for onKeyDown event       **
 ** target is the client id for the btn you want to click when **
 ** enter is clicked.                                          **
 ****************************************************************/ 
function btnClickOnEnterKeyDown(target, ev)
{
    var keyCode;
    if (ev) keyCode = (window.Event) ? ev.which : ev.keyCode;
    if (keyCode == 13) {
        try {
            $get(target).click();
        } catch (e) {}
    }
}

/****************************************************************
 ** Find Ancestor for which a function returns true *************
 ****************************************************************/ 
function FindAncestor(el, comparisonFunc)
{
    if (comparisonFunc(el) == true) return el;
    else if (el.parentNode) {
        return arguments.callee(el.parentNode, comparisonFunc);
    }
    else return false;  
}
/*******************************************************************************************
 ** Filters an array and returns all objects for which a function returns true *************
 *******************************************************************************************/
function FilterArray(arr, filterFunc)
{
    var ret = new Array();
    for (var i = 0; i < arr.length; i++) {
        if (filterFunc(arr[i]) == true) {
            ret[ret.length] = arr[i];
        }
    }
    return ret;
}

/*********************************************************************************
 ** Gets the bext sibling for an element for which the nodeType is 1 *************
 *********************************************************************************/
function GetNextSibling(el)
{
    var ret = el.nextSibling;
    while (ret.nodeType != 1) {
        ret = ret.nextSibling;
    }
    return ret;
}

/************************************************
 ** DHTML date validation script. ***************
 ************************************************/
// Declaring valid date character, minimum year and maximum year
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}
function isDate(_day,_month,_year)
{
	if (!isInteger(_day) || !isInteger(_month) || !isInteger(_year)) {
		//alert("Please enter a valid date");
		return false;
	}
	var daysInMonth = DaysArray(12);
	var strDay = _day;
	var strMonth = _month;
	var strYear = _year;
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) { strDay=strDay.substring(1); }
	if (strMonth.charAt(0)=="0" && strMonth.length>1) { strMonth=strMonth.substring(1); }
	
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) { strYr=strYr.substring(1); }
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (strMonth.length < 1 || month < 1 || month > 12) {
		//alert("Please enter a valid month");
		return false;
	}
	if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
		//alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
    return true;
}

/****************************************
 *** Very handy String methods **********
 ****************************************/
var StringHelper = {};
StringHelper.trim = function trim(str) {
    return str.replace(/^\s+|\s+$/g,'');
}
StringHelper.normalize = StringHelper.normalise = function normalize(str) {
    return StringHelper.trim(str).replace(/\s+/g,' ');
}
StringHelper.startsWith = function startsWith(str, value, caseSensitive) {
    var i = (caseSensitive) ? '' : 'i';
    var re = new RegExp('^' + value, i);
    return (StringHelper.normalize(str).match(re)) ? true : false;
}
StringHelper.endsWith = function endsWith(str, value, caseSensitive) {
    var i = (caseSensitive) ? 'gi' : 'i';
    var re = new RegExp(value + '$',i);
    return (StringHelper.normalize(str).match(re)) ? true : false;
}


/* Cross browser method for creating new DOM nodes with name attributes. This 
 * gets around an Internet Explorer bug that prevents that get the name property
 * assigned to them and their values aren't sent when the form submits. *
 
 * @param   string  required  Node name, like "div" or "input" 
 * @param   string  required  Value of the name attribute 
 * @return  object  New DOM node */
function createElement(nodeName, name)
{
    var node;
    try
    {
        node = createElementMsie(nodeName, name);
        createElement = createElementMsie;
    }
    catch (e)
    {
        node = createElementStandard(nodeName, name);
        createElement = createElementStandard;
    }
    return node;
}
/* Code required by Internet Explorer when creating a new DOM node with the name attribute set. */
function createElementMsie(nodeName, name)
{
    return document.createElement("<"+nodeName+" name=\""+name+"\">");
}
/* Code required by all other browsers that support web standards. */
function createElementStandard(nodeName, name)
{
    var node = document.createElement(nodeName);
    node.name = name;
    return node;
}

function enlargeIframe()
{
    var f = $get('ctl00_CurrentUser1_Registration1_frmViewRegistration');
    f.style.height = "515px";
    if(document.all)    f.style.height = "495px";
    BrowserDetect.init();

    if (BrowserDetect.version == 6) f.style.height ="545px";
    
}

function startUpLoginExtender(_LoginExtenderID)
{
    LoginExtenderID=_LoginExtenderID;
}
function startUpAlertExtender(_AlertExtenderID)
{
    AlertExtenderID=_AlertExtenderID;
}
function startUpAddCommentExtender(_AddCommentID)
{
    AddCommentID = _AddCommentID;
}
function startUpSendMessageExtender(_SendMessageID)
{
    SendMessageID = _SendMessageID;
}
function startUpSendMessageHidden(_SendMessageHiddenID)
{
    SendMessageHiddenID = _SendMessageHiddenID;
}

function startUpAddDiscussionExtender(_AddDiscussionID)
{
    AddDiscussionID = _AddDiscussionID;
}
function startUpAlertMessage(_AlertMessageID)
{
    AlertMessageID = _AlertMessageID;
}
function showAddCommentPopup()
{
    $find(AddCommentID).show();
}
function showSendMessagePopup(sendToName,sendToId,subject,text,replyOnId)
{
    $get("LabelSendToName").innerHTML = sendToName;
    $get(SendMessageHiddenID).value = sendToId;
    if (replyOnId)
        $get(SendMessageReplyToID).value = replyOnId;
    if (subject)
        $get(SendMessageSubjectID).value = subject;
    if (text)
    {
        $get(SendMessageTextID).value = text.replace(/<br.?\/>/g,'\n');
    }
    $find(SendMessageID).show();
}
function showAddDiscussionPopup()
{
    $find(AddDiscussionID).show();
}
function startUpRegisterExtender(_RegisterExtenderID)
{
    RegisterExtenderID=_RegisterExtenderID;
}
function showRegisterPopup()
{
try
    {
    $find(RegisterExtenderID).show();
    
    try{
    var top = "60px";
    // if explorer
    if (document.all) top = "80px";
    $get('ctl00_CurrentUser1_Registration1_mpnlRegister').style.top = top;
    }catch(ee){}
    
    try {
    var frame = document.getElementById("ctl00_CurrentUser1_Registration1_frmViewRegistration"); 
    var doc = frame.contentDocument;
    if (doc == undefined || doc == null)
        doc = frame.contentWindow.document;
    var tb = doc.getElementById("tbEmail");
    tb.focus();
        } catch (e) {}
    
    
    }
    
    
    catch(ex) 
    {
    alert ("You are logged in already");
    }
}
function showLoginPopup()
{
try
    {
    $find(LoginExtenderID).show();
    }
    catch(ex)
    {
    alert ("You are logged in already");
    }
}

function hideLoginShowRegister()
{
    try
    {
        $find(LoginExtenderID).hide();
    }
    catch(err){}
    
    showRegisterPopup();
}

function ShowRegisterIfNotLogged()
{
//confirm(COstatus);
    if (COstatus=='LOGGEDIN')
    {
        return true;
    }
    
    showRegisterPopup();
    return false;
}


function setStatus(_status)
{
    COstatus = _status;
}

function settbLoginHiddenID(_tbLoginHiddenID)
{
    tbLoginHiddenID = _tbLoginHiddenID;
}
function settbRegisterHiddenID(_tbRegisterHiddenID)
{
    tbRegisterHiddenID = _tbRegisterHiddenID;
}
function settbRegisterCloseHiddenID(_tbRegisterCloseHiddenID)
{
    tbRegisterCloseHiddenID = _tbRegisterCloseHiddenID;
}

function getCoupon()
{
    if (COstatus=='LOGGEDIN')
    {
        window.location="~/NodesPages/UserPages/Membership.aspx?openPopup=true";
    }
    else
    {
        //$get(tbLoginHiddenID).value = "getCoupon";
        setSessionParam("getCoupon","true");
        $find(LoginExtenderID).show();
    }
}

function useCoupon()
{
    if (COstatus=='LOGGEDIN')
    {
        window.location="~/NodesPages/UserPages/Membership.aspx";
    }
    else
    {
        //$get(tbLoginHiddenID).value = "useCoupon";
        setSessionParam("useCoupon","true");
        $find(LoginExtenderID).show();
    }
}

function registerContinue()
{
    //$get(tbRegisterHiddenID).value = parent.getLoginHiddenValue();
    window.parent.eval("setStatus('LOGGEDIN')");
}

function getLoginHiddenValue()
{
    try
    {
        return $get(tbLoginHiddenID).value;
    }
    catch (e) {return "";}   
}

function alert(x)
{
    alert(x,false);
}

function alert(x,hideClose)
{
    alert(x,hideClose,'');
}

function alert(x,hideClose,className)
{
    while (x.indexOf("***",0) != -1)
    {
        x = x.replace("***","'");
    }

    var AlertExtender = $find(AlertExtenderID);
    AlertExtender.show();

    if(hideClose)
        $("*.closeBtn").hide();

    var am = $get(AlertMessageID);
    am.className = className;
    am.innerHTML = x;
}

function closeAlert()
{
    $find(AlertExtenderID).hide();
}

function popGetVoucher(cashTrophies)
{
    //var iframe = document.getElementById('iframeGetAFreeVoucher');
    //iframe.src = "http://www.codeoasis.com";
    var alertContent = "<iframe id='iframeGetAFreeVoucher' src='~/NodesPages/Misc/GetAFreeVoucher.aspx";
    if (cashTrophies)
        alertContent += "?cashTrophies=yes";
    alertContent += "' width='413x' height='270px' frameborder='0' scrolling='no'></iframe>";
    alert(alertContent,true);
}

function showCognitivePopup()
{
$find(CogScoreExtenderID ).show();}

function startUpCogScoreExtender(extenderID)
{
    CogScoreExtenderID = extenderID;
}

function LoginPopupRedirectNoReturn(link)
{
    if (link=='') link = window.location;
    var isLoggedIn = $get('DIV_LOGGED');
    if (isLoggedIn!=null)
    {
        window.location = link;
        return true;
    }
    //else
    //$get(tbLoginHiddenID).value = "link:"+link;
    //otherwise id there are params in the link they doesn't pass (alissa)
    link = link.replace("&","%26");
    setSessionParam("redirectAfterLogin",link);
    
    $find(LoginExtenderID).show();
    try {
    $get('ctl00_CurrentUser1_Login1_LoginInner1_tbEmail').focus();
        } catch (e) {}
}

function LoginPopupRedirect(link)
{
    LoginPopupRedirectNoReturn(link);
    return false;   
}
function LoginPopupRedirectNoReturnNewWindow(link)
{
    if (link=='') link = window.location;
    var isLoggedIn = $get('DIV_LOGGED');
    if (isLoggedIn!=null)
    {
        window.open(link);
        return true;
    }
    //else
    //$get(tbLoginHiddenID).value = "link:"+link;
    //otherwise id there are params in the link they doesn't pass (alissa)
    link = link.replace("&","%26");
    setSessionParam("redirectAfterLogin",link);
    
    $find(LoginExtenderID).show();
    try {
    $get('ctl00_CurrentUser1_Login1_LoginInner1_tbEmail').focus();
        } catch (e) {}
}

function LoginPopupRedirectNewWindow(link)
{
    LoginPopupRedirectNoReturnNewWindow(link);
    return false;   
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function alertDiv(divId)
{
    alertDiv(divId,false);
}
function alertDiv(divId, hideClose)
{
	var div1 = document.getElementById(divId);
	alert(div1.innerHTML,hideClose,divId);		
}
function ValidateComment(source, args)
{
   args.IsValid = (args.Value.length<1800);
} 

