if(typeof(bInEditMode)==='undefined') bInEditMode=false;

//Domain stuff for iframe intercommunication
var sLowerD = location.host.toLowerCase();
var sLowerDNoPrefix = sLowerD.replace(/^glyph.|^www./,"");
var sDD = (location.port == 80 || location.port == 443) ? sLowerDNoPrefix : sLowerDNoPrefix;
//document.domain = sDD;



$().ready(function() {
	launchForeignSitesInNewWin();
	doStartupFunctions();
	checkLinks();
});


function checkLink(oLink){
	//look for links that could break our a column
	if(window.console){console.log("Checking link:",oLink)}
	if(!oLink.childNodes){
		if(window.console)console.log("no access to childNodes collection");
		return;
	};
	var $oLink = $(oLink);
	var sLinkText = $.trim($(oLink).text());
	var nChildNodes = oLink.childNodes.length;
	var firstChildNodeType = (oLink.childNodes[0]) ? oLink.childNodes[0].nodeType : false;
	var nLinkWidth = ($.browser.msie) ? oLink.offsetWidth : $oLink.width() ;
	if(nChildNodes==1 && firstChildNodeType==3){
		//now we know its a text only link
		var wspaceRE = new RegExp(/\s/);
		var bHasWhiteSpace = wspaceRE.test(sLinkText);
		if(!bHasWhiteSpace){
			//now we know there is no whitespace
			var closestDiv = $oLink.closest("div");
			var nColumnWidth = getColumnWidth(closestDiv);
			//if($oLink.width() > nColumnWidth){
			if(nLinkWidth > nColumnWidth){
				//now we know the link is wider than it should be, we need to truncate it
					//if(window.console)console.log("link width:",$oLink.width(),"is wider than column width:",nColumnWidth);
					if(window.console)console.log("link width:",nLinkWidth," is wider than column width:",nColumnWidth);
					
				sShorterText = sLinkText.substring(0,30) + "...";
				
				if(window.console){
					console.log("~~~~~");
					console.log("Its a text only link with no whitespace!");
					//console.log("oLink:",oLink);
					console.log("$(oLink).text():",$(oLink).text());
					console.log("replacing with:",sShorterText);
				}
				 $(oLink).text(sShorterText);
			} else {
				//if(window.console)console.log("link width:",$oLink.width(),"is NOT wider than column width:",nColumnWidth);
				if(window.console)console.log("link width:",nLinkWidth," is supposedly NOT wider than column width:",nColumnWidth);
				if(nColumnWidth == 278 && !$.browser.mozilla && sLinkText.length >= 40){
					if(window.console)console.log("suspected false link width combined with long unbroken link text, so truncating link text");
					sShorterText = sLinkText.substring(0,40) + "...";
					$(oLink).text(sShorterText);
				}
			}
		}
	} else {
		if(window.console){
			console.log(oLink, " couldnt satisfy: nChildNodes==1 && firstChildNodeType==3; meaning doenst appear to be a text only link");
			console.log("nChildNodes:",nChildNodes);
			console.log("firstChildNodeType:",firstChildNodeType);
			console.log("---");
		}
	}
}
function checkLinks(){
	//I tried $(".info_rightcol a , .directory_half a").each(...) but no go
	checkHalfColumnLinkLengths();
	checkRightColumnLinkLengths();
	checkThirdsColumnLinkLengths();
}
function checkRightColumnLinkLengths(){
	$(".info_rightcol a").each(function(){
		checkLink(this);
	});
}
function checkHalfColumnLinkLengths(){
	$(".directory_half a").each(function(){
		checkLink(this);
	});
}
function checkThirdsColumnLinkLengths(){
	$(".directory_third a").each(function(){
		checkLink(this);
	});
}
function returnEditMode(){
	return bInEditMode;
}

function launchForeignSitesInNewWin(){
	$("a").live("click",function(e){
		if(e.button == 0){ //right click was triggering this on Mac Firefox so this check became necessary
			var currentHref=this.href.toLowerCase();
			if(currentHref.indexOf("http")==0 && (currentHref.indexOf("strose.edu")==-1 && currentHref.indexOf("futuremediainteractive.com")==-1 )){
				window.open(this.href);
				return false;
			}
		}
	});
	/*
	//var domainMatch = /http:\/\/([a-zA-Z0-9_-]+\.)?(strose|futuremediainteractive)\.(edu|com)/i;
	$('a').each(function() {		
		var currentHref=this.href.toLowerCase();
		if(currentHref.indexOf("http")==0 && (currentHref.indexOf("strose.edu")==-1 && currentHref.indexOf("futuremediainteractive.com")==-1 ))
		//if( this.href.match(domainMatch) === null)	
				{ 
					$(this).click(function() {
						//console.log("this href = "+this.href+"match = "+this.href.match(domainMatch));
						window.open(this.href);
						return false;
					});
				}
	});	
	*/

}

function loginInPlace(f){
	$("#loginb").attr("value","Checking...");
	var sErrorPreamble = "<img src='/img/loginAlert.png' width='23' height='21' border='0' alt='Login failed:' hspace='3' /> "; 
	var sErrorMessage = [];
	if(isEmptyOrWhitespace(f.email.value)) {
		sErrorMessage[sErrorMessage.length] = "Please enter your email address. ";
	} else if(!isValidEmailAddress(f.email.value)){
		sErrorMessage[sErrorMessage.length] = "Please check that the email address you provided is correct. ";
	}
	if(isEmptyOrWhitespace(f.p.value)) {
		sErrorMessage[sErrorMessage.length] = "Please enter your password.";
	}
	if(sErrorMessage.length===0){
		$("#loginfeedback").html("");
		//sData needs to be an object so that jQuery can properly encode the POST vars
		var sData = { email: f.email.value, p:f.p.value };
		$.ajax({
			type: "POST",
			url: "/LoginAjax.aspx",
			data: sData,
			success: function(response){
				//alert( "server said in char 0: " + response.charAt(0) + "\nserver said: " + response);
				if(response==="1"){					
					location.reload(true);
				} else {				
					//alert('O snap, that login is wack!');
					$("#loginfeedback").html(sErrorPreamble + " The login or password you typed is incorrect.").slideDown("fast");
					$(f).shake(2, 10, 200);
					$("#loginb").attr("value","GO");
				}
			}
		});
	} else {
		sErrorFeedbackMessage = sErrorPreamble + sErrorMessage.join(" ");
		$("#loginfeedback").html(sErrorFeedbackMessage).slideDown("fast");
		$(f).shake(2, 10, 200);
	}
}

function resizeFlashTags(sModuleID,desiredwidth,desiredheight){
	var $moduleDiv = $("#m"+sModuleID);
	$("object,embed",$moduleDiv).attr("width",desiredwidth).attr("height",desiredheight);	
}

function getColumnWidth(oModuleDiv){
	var oClosestTD = $(oModuleDiv).closest("td");
	var nColumnWidth = 0;
	var nMinWidth=100;
	//if(window.console)console.log("oClosestTD.get(0):",oClosestTD.get(0));
	if(oClosestTD.get(0)){
		if(oClosestTD.hasClass("info_rightcol")){
			nColumnWidth = 278;//279
		} else if(oClosestTD.hasClass("info_centercol")){
			nColumnWidth = 367;//390;
		} else if(oClosestTD.hasClass("directory_half")){
			nColumnWidth = 328;
		} else if(oClosestTD.hasClass("directory_third")){
			nColumnWidth = 204;
		} else if(oClosestTD.hasClass("info_full") || oClosestTD.hasClass("fullwidth")){
			nColumnWidth = 655;//665;
		}
	}else{
		oClosestContainer =  $(oModuleDiv).closest("div");
		nColumnWidth = oClosestContainer.width();
	}
	if(nColumnWidth==0){nColumnWidth=nMinWidth}
	return nColumnWidth;
}

function sizeingIframe(sIframeID,attempt){
	//return true;
	if(window.console)console.log('sizeingIframe(',sIframeID,')');
	if(!attempt){attempt=1};
	if(window.console)console.log('attempt:',attempt);

	var extraheight = 35;
	//var minPortalHeight = 500;
	var minPortalHeight = 25;
	
	$("#"+sIframeID).contents().find("body").append("<div id='bottom"+sIframeID+"'></div>");
	//var currentPort = location.port;

	if(document.all){
		try{	
			var oIframe = document.getElementById(sIframeID);
			var nTargetHeight = oIframe.contentWindow.document.body.scrollHeight;
			nTargetHeight = (nTargetHeight < minPortalHeight) ? minPortalHeight : nTargetHeight;
			if(window.console)console.log("nTargetHeight:",nTargetHeight);
			oIframe.style.height = nTargetHeight + "px";
		} catch(e) {
			//An error is raised if the IFrame domain != its container's domain
			if(window.console){
				console.log('Could not resize the iframe to content size: ',e.number,'; ',e.description);
			} else {
				window.status =	'Could not resize the iframe to content size: ' + e.number + '; ' + e.description;
			}
			var leftnavheight = $("#leftsubnav").height();
			leftnavheight = (leftnavheight < minPortalHeight) ? minPortalHeight : leftnavheight;
			$("#"+sIframeID).height(leftnavheight);
		}
	} else {
		try {
			var oIframe = document.getElementById(sIframeID);
			if(oIframe.style.display != 'none'){
				var iframeParentHeight = $(oIframe.parentNode).height();	
				
				var iframeBodyHeight = $(oIframe).contents().find("body").height();
				var iframeHTMLHeight = $(oIframe).contents().find("html").height();
				var iframeContentHeight = (iframeHTMLHeight) ? (iframeHTMLHeight > iframeBodyHeight) ? iframeHTMLHeight : iframeBodyHeight :iframeBodyHeight ;
				
				if(window.console){
					console.log('sIframeID:',sIframeID);
					console.log('oIframe:',oIframe);
					console.log('oIframe parent:',oIframe.parentNode);
					console.log('iframeParentHeight:',iframeParentHeight);
					console.log('iframeHTMLHeight:',iframeHTMLHeight);
					console.log('iframeBodyHeight:',iframeBodyHeight);
					console.log('iframeContentHeight:',iframeContentHeight);
					console.log('------');
				}
				var nTargetHeight = (iframeContentHeight+extraheight < minPortalHeight) ? minPortalHeight : iframeContentHeight+extraheight;

				$(oIframe.parentNode).height(nTargetHeight);
				$(oIframe).height(nTargetHeight);

			}	
		} catch(e){
			if(window.console){
				console.log('Could not resize the iframe to content size: ',e.number,'; ',e.description);
			} else {
				window.status =	'Could not resize the iframe to content size: ' + e.number + '; ' + e.description;
			}
			var leftnavheight = $("#leftsubnav").height();
			leftnavheight = (leftnavheight < minPortalHeight) ? minPortalHeight : leftnavheight;
			$("#"+sIframeID).height(leftnavheight);
		}
	}
	
	if(($.browser.msie || $.browser.safari) && attempt <=2){
		if($.browser.msie){
			if(window.console){console.log("setTimeout instead of animate delay")}
			var sFun = "sizeingIframe('"+sIframeID+"',"+(attempt+1)+")";
			setTimeout(sFun,3000);
		}else{
			$("#"+sIframeID).animate({opacity:1.0},3000,"linear",function(){sizeingIframe(sIframeID,attempt+1)})
		}		
	}
}

//utils
function gup(name){
	//get url parameter
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ) {
		return "";
	} else {
		return results[1];
	}
}
function gupCaseInsensitive(name){
	//get url parameter
	var currentUrl = window.location.href;
	var lowerCurrentUrl = currentUrl.toLowerCase();
	name = name.toLowerCase();
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( lowerCurrentUrl );
	if( results == null ) {
		return "";
	} else {
		return results[1];
	}
}

function returnFalse(eventObject){
	return false;
}

function log(sString){
	if(window.console){console.log('Flash: ',sString);}
}

function removeSubString(s, t) {
  // Remove all occurrences of a token in a string
  // s  string to be processed
  // t  token to be removed
  // returns new string
  i = s.indexOf(t);
  r = "";
  if (i == -1) return s;
  r += s.substring(0,i) + removeSubString(s.substring(i + t.length), t);
  return r;
}

function replaceQueryString(url,param,value) {
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
    if (url.match(re)){
        return url.replace(re,'$1' + param + "=" + value + '$2');
	} else {
        return url + '&' + param + "=" + value;
	}
}

var whitespace = " \t\n\r";
var digits = "0123456789";
function isEmpty(s) {   
	return ((s == null) || (s.length == 0))
}
function isEmptyOrWhitespace (s) {   
	var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++) {   
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}
function isValidEmailAddress(s) {
	var temp = s.replace(/\s/g, "")
	return (temp.match(/^[\w\.\-]+\x40[\w\.\-]+\.\w{2,3}$/)) && 
			temp.charAt(0) != "." && !(temp.match(/\.\./))
}


jQuery.log = function(message) {
  if(window.console) {
     //console.debug(message);
	 console.log(message);
  } else {
     //alert(message);
  }
};

jQuery.fn.shake = function(intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {
	this.each(function() {
		$(this).css({position:'relative'});
		for (var x=1; x<=intShakes; x++) {
			$(this).animate({left:(intDistance*-1)}, (((intDuration/intShakes)/4)))
				.animate({left:intDistance}, ((intDuration/intShakes)/2))
				.animate({left:0}, (((intDuration/intShakes)/4)));
		}
	});
	return this;
};

if(typeof Array.indexOf != 'function') {
	Array.prototype.indexOf = function(f, s) {
		if (typeof s == 'undefined') s = 0;
		for (var i = s; i < this.length; i++) {
			if (f === this[i]) return i;
		}
		return -1;
	}
}