var quickLaunch;
var quickTourDirectory = "";
var legalDirectory = "";

FeaturesParam = function(left, top, width, height, scrollbars, resizable, menubar, toolbar, location)
{
			this.left=left; 
			this.top=top;
			this.width=width;
			this.height=height;
			this.scrollbars=scrollbars;
			this.resizable=resizable;
			this.menubar=menubar;
			this.toolbar=toolbar;
			this.location=location;
			this.featuresParamString=function(){
				var featuresParam='';
				if(this.left)
					featuresParam+='left='+this.left+',';
				if(this.top)
					featuresParam+='top='+this.top+',';
				if(this.width)
					featuresParam += 'width='+this.width+',';
				if(this.height)
					featuresParam += 'height='+this.height+',';
				if(this.scrollbars)
					featuresParam += 'scrollbars='+this.scrollbars +',';
				if(this.resizable)
					featuresParam += 'resizable='+this.resizable+',';
				if(this.menubar)
					featuresParam += 'menubar='+this.menubar+',';
				if(this.toolbar)
					featuresParam += 'toolbar='+this.toolbar+',';
				if(this.location)
					featuresParam += 'location='+this.location+',';
				
				//just in case a comma was appended with nothing behind it
				var lastCommaIndex=featuresParam.lastIndexOf(',');
				if( (featuresParam.charAt(lastCommaIndex+1) == undefined) ||
					(featuresParam.charAt(lastCommaIndex+1) == null) ||
					(featuresParam.charAt(lastCommaIndex+1) == '')
				 ) //||
				{
					featuresParam[lastCommaIndex]='';
				}
				
				return featuresParam;				
			}
			
};

var windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
var windowWidth = $(window).width();

function openLink(theURL, name, params, reopen){
 //note: won't use reopen for now 
	var wname = (name ? name : '');
	
	var winfeatures = new FeaturesParam('20','20','700',.6*windowHeight,1,1,1,1,1);;
	if(params != '')
		winfeatures = params;
	else{
		if((wname != null) && (wname != "")){
			wnameLower=wname.toLowerCase();
			
			if(wnameLower == "external") { //external websites
				var externalfeatures=new FeaturesParam('30','30','700',.6*windowHeight,1,1,1,1,1);
				winfeatures=externalfeatures;
			} 
			else if(wnameLower  == "worksheet"){ //i.e. worksheets
				theURL += "&resourceID=" + quickLaunch;
				winfeatures=new FeaturesParam('40','40','700',.5*windowHeight,1,1,0,0,0);
			}
			else if(wnameLower  == "filelink"){ //i.e. materials in IAs
				var filelinkfeatures=new FeaturesParam('30','30','700', windowHeight,1,10,0,0);
				winfeatures=filelinkfeatures;
			}
			else if(wnameLower  == "quiz" || wnameLower  == "quizanswers" || wnameLower  == "transcript" || wnameLower  == "respond" || wnameLower  == "respondanswers"){ //i.e. ai quizzes
				var quizfeatures=new FeaturesParam('30','30','700','400',1,1,0,0,0);
				winfeatures=quizfeatures;
			}
			else if(wnameLower  == "audioinquiryquiz"){ //i.e. audio inquiry quiz
				
				var audioinquiryquizfeatures = new FeaturesParam('20','0','680',windowHeight,1,1,0,0,0); 
				winfeatures=audioinquiryquizfeatures;
			}
			else if(wnameLower  == "help"){ //i.e. 
				
				var helpfeatures = new FeaturesParam('20','0','700',windowHeight,1,1,0,0,0); 
				winfeatures=helpfeatures;
			}
			else if(wnameLower  == "contactus"){ //i.e. 
				winfeatures=new FeaturesParam('20','0','700','500',1,1,0,0,0);
			}
			else if(wnameLower  == "subscribe"){ //i.e. 
				
				var subscribefeatures = new FeaturesParam('20','0','950',windowHeight,1,1,0,0,0); 
				winfeatures=subscribefeatures;
			}
			else if(wnameLower  == "systemcheck"){ //i.e. system check
				
				//THIS DEPENDS ON login.js
				   if(!isAuthenticated())
				   {
				   		
					   showLoginForm(function() {
				   			openLink(theURL, name, params, reopen);
				   		});
				   		return null;
				   }
				var systemcheckfeatures = new FeaturesParam('0','0','700','600',1,1,0,0,0); 
				winfeatures=systemcheckfeatures;
			}
			else if(wnameLower  == "english" || wnameLower  == "math" || wnameLower  == "ss" || wnameLower  == "science" || wnameLower  == "spanish" || wnameLower  == "all" || wnameLower  == "printlist"){ //i.e. at a glance
				winfeatures = new FeaturesParam('10','10','963','400',1,1,0,0,0);
			}
			else if(wnameLower  == "english_plan" || wnameLower  == "math_plan" || wnameLower  == "ss_plan" || wnameLower  == "science_plan" || wnameLower  == "spanish_plan"){ //i.e. plan books
				winfeatures = new FeaturesParam('10','10','750','490',0,0,0,0,0);
			}
		}	
	}

	var launchParams = winfeatures.featuresParamString();

	popupWindow = window.open(theURL, name, launchParams);
	popupWindow.focus();
	return popupWindow;
}

function showMessageDialog(message, callback)
{
   	$("#message-dialog").dialog({
				modal: true,
				buttons: {
					OK: function() {
						$(this).dialog('close');
						if(callback) callback();
					}
				},
				width: message.width,
				height: message.height,
				title: message.title,
				position: [message.left,message.top],
				close: function (e, ui) {$("#message-dialog > a").unbind('click');},
				dialogClass: message.msgClass	
	});
	$("#message-dialog").html(message.text);
	$("#message-dialog > a").bind('click', function(e){$("#message-dialog").dialog('close');});	
}


function showFormDialog(form, focusElement)
{
	var divid = "div#" + form.divid;
	
 	$(divid).dialog({
				modal: form.modal,
				width: form.width,
				title: form.title,
				resizable: false,
				beforeClose: function (e, ui) {$(".ui-widget-overlay").removeClass('login-overlay');},
				close: function (e, ui) {$(".close-prompt").unbind('click');},
				dialogClass: form.dialogClass
	});
	//The center position for dialog is not working in safari, and the $(window).height is also not working
	var t = document.documentElement.clientHeight  > $(divid).height() ? document.documentElement.clientHeight /2.5 - $(divid).height()/2 : 0;
	var l = $(window).width() > $(divid).width() ? $(window).width()/2 - $ (divid).width()/2 : 0;
	$(divid).dialog( "option", "position", [l, t] );	
	$(focusElement).focus();
	$(focusElement).attr('value',$(focusElement).attr('value'));  //PUT CURSOR AT END
	$(".close-prompt").bind('click', function(e){$(divid).dialog('close');});
	if(form.modal) $(".ui-widget-overlay").addClass('login-overlay');
}
function openLessonGuideByID(urlFrag, paramName, paramElementName, supplemental, showSpanish)
{
	url = urlFrag + '?' + paramName + '=';
	resourceID = paramElementName;
	url += resourceID + "&lessonguide=true";
	if(supplemental)
		url += "&supplemental="+ supplemental;	
	if(showSpanish)
		url += "&showSpanish="+ showSpanish;
	var launchParams = new FeaturesParam('20', '20', 700, 400, 1, 1, 0, 0, 0);
	if(supplemental){
		launchParams = new FeaturesParam('30', '30', 700, 400, 1, 1, 0, 0, 0);
		openLink(url, supplemental, launchParams, true);	
	}
	else
		openLink(url, 'lessonguide', launchParams, true);
}
function openResourceByID(urlFrag, paramName, paramElementName, byPassAuth, reopenWindowName)
{
   var validResourceID = true;
   url = urlFrag + '?' + paramName + '=';
   //byPassAuth is for launching resources from TBLs
   if(!byPassAuth){
	   //THIS DEPENDS ON login.js
	   if(!isAuthenticated())
	   {
	   		showLoginForm(function() {
	   			openResourceByID(urlFrag, paramName, paramElementName, '', reopenWindowName);
	   		});
	   		return;
	   }
   }
    
   if(document.getElementById(paramElementName) != null)
   {
	   resourceID = escape(document.getElementById(paramElementName).value);
	   
	  if(isNaN(parseInt(resourceID)))
	   {
	   
	       alert('You must enter a number.');
	       validResourceID = false;
	   }
   }
   else
   {
   		resourceID = paramElementName;
   }

   if(validResourceID)
   {
       url += resourceID;
	   var windowName = 'resource' + resourceID;
	   var activityRatioHeight, activityRatioWidth;
	   var launchHeight=460;
	   var launchWidth=700;
	   var h = window.innerHeight ? window.innerHeight : $(window).height();
	   var w = $(window).width();
	   $.ajax({ 
		   url: urlFrag, 
		   async: false, 
	       dataType: 'json',
	       data: {action: "lookup", id: resourceID}, 
	       success: function (resource) {
	    	   if((resource != null) && (resource.status == true)){
	    		   if(resource.windowName != null)
	    			  windowName = resource.windowName;
	    		   if(resource.type == "InterActivity"){ 
	    			   
	    			   launchHeight = h;
		    		   launchWidth = w;
			    	   if(resource.height != 0){ //dynamic sizing
			    		   activityRatioHeight = resource.height;
			    		   activityRatioWidth = resource.width;
			    		   var multiplier = Math.floor(w/activityRatioWidth);
			    		   launchWidth = activityRatioWidth*multiplier;
			    		   launchHeight = activityRatioHeight*multiplier;
				        	if(launchHeight > h){
				        		 multiplier = Math.floor(h/activityRatioHeight);
				        		 launchWidth = activityRatioWidth*multiplier;
				        		 launchHeight = activityRatioHeight*multiplier;
				        	}
			    	   }
			    	   else if (resource.minHeight != 0){ //resources that have an exact launch size
			    		   launchHeight = resource.minHeight;
			    		   launchWidth = resource.minWidth;
			    	   }
	    		   }
	    		   else if(resource.type == "AudioInquiry") { 
	    			   
	    			   var multiplier = Math.floor(h/3);
		    		   launchWidth = 4*multiplier;
		    		   launchHeight = 3*multiplier;
	    		   }
	    		   else {
				  		//text based resources
				  		launchHeight = h;
				  		launchWidth = 900;
	    		   }
	    		   if(launchWidth < 875)
	    			   launchWidth= 875;
	    	   }
	    	   else{ //retired, invalid, coming soon
	    		   launchHeight=460;
	    		   launchWidth=700;
	    	   }
	       }
	   });
	   var launchParams = new FeaturesParam('0', '0', launchWidth, launchHeight, 1, 1, 0, 0, 0);
	   if(reopenWindowName != undefined){
		   windowName = reopenWindowName;
	   }
	  
	   openLink(url, windowName, launchParams);
   }
}

function setQuickTourDirectory(path){
	quickTourDirectory = path;
}
function setLegalDirectory(path){
	legalDirectory = path;
}
function setQuickLaunchID(id){

	quickLaunch = id;
}
function openQuickTourWindow(){
	
	if(quickLaunch != null){
		
		var url = quickTourDirectory + "/index.jsp?resourceID=" + quickLaunch;
		var quicktourfeatures=new FeaturesParam('0','0','520','405',0,0,0,0,0);
		openLink(url, 'quicktour', quicktourfeatures, true);
	}
	else
		alert("no quick launch id given");
}

function openLegalNoticesWindow(){
	if(legalDirectory != null){
		var url = legalDirectory + "/index.jsf";
		var legalfeatures=new FeaturesParam('0', '0', '675', '400', 1, 1, 0, 0, 0);
		openLink(url, 'legal', legalfeatures, true);
	}
}
function openPrivacyNoticeWindow(){
	if(legalDirectory != null){
		var url = legalDirectory + "/privacyNotice.jsf";
		var legalfeatures=new FeaturesParam('0', '0', '675', '400', 1, 1, 0, 0, 0);
		openLink(url, 'legal', legalfeatures, true);
	}
}
function openTermsOfUseWindow(){
	if(legalDirectory != null){
		var url = legalDirectory + "/termsOfUse.jsf";
		var legalfeatures=new FeaturesParam('0', '0', '675', '400', 1, 1, 0, 0, 0);
		openLink(url, 'legal', legalfeatures, true);
	}
}
function openProfileWindow(){
	var theFeatures=new FeaturesParam('0', '0', '750', '500', 1, 1, 0, 0, 0);
	openLink(CONTEXT_ROOT+'/profile/index.jsf', 'profile', theFeatures, true);
}
function openVerifyEmailWindow(){
	var theFeatures=new FeaturesParam('0', '0', '640', '400', 1, 1, 0, 0, 0);
	openLink(CONTEXT_ROOT+'/profile/profileverificationemail.jsf', 'profile', theFeatures, true);
}
function openLoginAssistanceWindow(){
	var theFeatures=new FeaturesParam('0', '0', '640', '400', 1, 1, 0, 0, 0);
	openLink(CONTEXT_ROOT+'/help/loginassistance/index.jsf', 'loginassistance', theFeatures, true);
}
function openContactUsWindow(){
	var theFeatures=new FeaturesParam('0', '0', '680', '425', 1, 1, 0, 0, 0);
	openLink(CONTEXT_ROOT+'/help/contactus/index.jsf', 'contactus', theFeatures, true);
}
function openHelpWindow(){
	var theFeatures=new FeaturesParam('0', '0', '850', windowHeight, 1, 1, 0, 0, 0);
	openLink(CONTEXT_ROOT+'/help/index.jsf', 'help', theFeatures, true);
}
function openImportantNoticesWindow(){
	var theFeatures=new FeaturesParam('0', '0', '640', '700', 1, 1, 0, 0, 0);
	openLink(CONTEXT_ROOT+"/home/importantNotices.jsf", 'importantNotices', theFeatures, true);
	$(".notices-importantNotices").css("display", "none");
}
function loadInParent(feature){
	var domain = window.location.host.toString();
	if(window.opener != null){
		var openerDomain = window.opener.location.host.toString();
		if(domain == openerDomain){
			window.opener.loadLink(feature);
			window.opener.focus();
		}
		else
			openLink("http://" + domain + '/' +CONTEXT_ROOT + "/#/" + feature, "SASCurriculumPathways", '');
	}
	else
		openLink("http://" + domain + '/' + CONTEXT_ROOT+ "/#/" + feature, "SASCurriculumPathways", '');
}
function openInstallWindow(installerLocation)
{
	if(installerLocation != null)
	{
		var installFeatures=new FeaturesParam('0', '0', '640', '400', 1, 1, 0, 0, 0);
		openLink(installerLocation, 'install', installFeatures, true);
	}
}

function openPluginWindow(aggreementLocation)
{
	if(aggreementLocation != null)
	{
		var theFeatures=new FeaturesParam('0', '0', '640', '400', 1, 1, 0, 0, 0);
		openLink(aggreementLocation, 'agreement', theFeatures, true);
	}
}
function openRetiredResources()
{
		var theFeatures=new FeaturesParam('0', '0', '640', '400', 1, 1, 0, 0, 0);
		openLink(CONTEXT_ROOT+'/help/retiredResources2011.pdf', 'retired', theFeatures, true);
}
function openRenumberedResources()
{
		var theFeatures=new FeaturesParam('0', '0', '640', '400', 1, 1, 0, 0, 0);
		openLink(CONTEXT_ROOT+'/help/renumberedResourcesMATH.pdf', 'renumbered', theFeatures, true);
}
function openDrGVideo()
{
		var theFeatures=new FeaturesParam('0', '0', '1000', '600', 1, 1, 0, 0, 0);
		openLink('http://www.youtube.com/user/SASsoftware#p/u/1/gD_tGC4v2V0', 'drgoodnight', theFeatures, true);
}
function isAuthenticated() 
{
	var loginServiceUrl = CONTEXT_ROOT + "/Login";
	var loginStatus = "UNAUTHENTICATED";
	//USE AN AJAX CALL W/ ASYNC = FALSE TO WAIT FOR THE RESPONSE
	$.ajax({
  		type: 'POST',
  		url: loginServiceUrl,
  		data: {action: "verify"},
  		success: function(data){loginStatus = data.status;},
  		dataType: "json",
  		async: false
	});
	
	return loginStatus == "AUTHENTICATED";
}

function exitConfirm()
{
	return "Before closing the browser, click Save, Print, E-mail to preserve your work.  Otherwise, your work will be lost.";
		
}
var contextRoot;
function setContextRoot(root)
{
	contextRoot = root;
}
function openStandardsForResource()
{
	if(quickLaunch != null){
		var url = contextRoot + "/standards/standardsFromResource.jsf?resourceID=" + quickLaunch;
		var standardsfeatures = new FeaturesParam('0','0','880','420',1,1,0,0,0);
		openLink(url, 'standards', standardsfeatures, true);
	}
	else
		alert("no quick launch id given");
}

var headerDialogWindow = null;
function openHeaderDialog(dialogName, height)
{	
	if (dialogName != "share" && dialogName != "favorites" && dialogName != "currentFavorites")
	{
		return;
	}
	if (quickLaunch == null)
	{
		return;
	}
	
	if (headerDialogWindow != null)
	{
		headerDialogWindow.close();
		headerDialogWindow = null;
	}
	
	var theFeatures=new FeaturesParam('0', '0', '532', height, 1, 1, 0, 0, 0);
	var url = CONTEXT_ROOT + "/render/dialogPopup.jsf?dialogName="+dialogName+"&resourceID="+quickLaunch+"&id="+quickLaunch;
	headerDialogWindow = openLink(url, 'dialogPopup', theFeatures, true);
}
