// KT This file now requires that apis3/prototype.js be in place as well..
// it is needed for AJAX API that allows us to call some AJAX functions

document.domain = "bfwpub.com";

var urlStart = location.href.substr(0, location.href.lastIndexOf("/")) + "/";		// urlStart + "filename.html");
var urlStartBookID = location.href.substr(0, location.href.lastIndexOf("/")) + "/" + bookId + "/";		// urlStart + "filename.html");

// KC: urlStart has the http:// prefix.  We'll have to strip that to get purchaseBaseURL (which is just a domain, and will be preceded by https://, not http://)
// FIX ME: Later we can prepend https:// to purchaseBaseURL and remove all the instances appearing below
var purchaseBaseURL = "";
purchaseBaseURL = urlStart;
purchaseBaseURL = purchaseBaseURL.replace("http://", "");
// also strip the trailing slash
purchaseBaseURL = purchaseBaseURL.replace("/", "");
// and replace ebooks with purchase
purchaseBaseURL = purchaseBaseURL.replace("ebooks", "purchase");

//alert("purchaseBaseURL: " + purchaseBaseURL);


// Set this so that opener.username will have a value in the supplemental window.
var username = "loginwindow";

function LoginOK() {
	var username;
	if (document.loginForm.username.value == '') {
		alert("You must enter a valid username and password to enter the site.");
		return false;

		if (confirm('You didn\'t enter a username.  Would you like to log in as a Guest (Preview mode)?')) {
			username = "Guest";
			document.loginForm.username.value = "Guest";
		} else {
			document.loginForm.username.select();
			return false;
		}
	} else {
		username = document.loginForm.username.value;
	}
	
	if (username != 'Guest' && username != 'guest' && document.loginForm.password.value == '') {
		alert("You must enter a valid username and password to enter the site.");
		return false;

		if (confirm('You didn\'t enter a password.  Would you like to log in as a Guest (Preview mode)?')) {
			username = "Guest";
			document.loginForm.username.value = "Guest";
		} else {
			document.loginForm.password.select();
			return false;
		}
	}

	if (document.loginForm.password.value.search(/<|>/) > -1){
		alert("That password contains illegal characters.  If you need assistance logging in please contact techsupport at (800)-936-6899 to have this corrected.");
		return false;
	}
	
	// store the user's username and siteVersion
	StoreCookie("lfiofoe", username);

	if(bookId == "physse6e"){
		var tosAccepted = GetTerms();

		// insert wiki legal pop
		//if( (tosAccepted != 1 && GetCookieVal(bookId + "_legal") != 1) ){
		if( tosAccepted != 1 ){
			ShowWikiTOS(bookId);
			return false;
		}	
	}
	return true;
}

function LoginFromReg(u, p) {
	document.loginForm.username.value = u;
	document.loginForm.password.value = p;
	LoginOK();	// stores the username cookie
	document.loginForm.submit();
	suppwin.close();
}

var suppwin;
function ShowSupp(page) {
	var fullPage;

	// Get fullPage for old style purchase/register pages
	// If page doesn't have a / in it, add "purchase/" to the start
	if (page.indexOf("/") == -1) {
		fullPage = "https://" + purchaseBaseURL + "/purchase/" + page + ".php?bookId=" + bookId + "&bookBase=" + bookBase;
	} else {
		fullPage = page + ".php?bookId=" + bookId + "&bookBase=" + bookBase;
	}

	// now replace some with new urls now that we're using RA
	// also note that we're using the staging URL for QA
	if (page == "purchase") {
		// fullPage = "https://purchase.bfwpub.com/purchase/transaction/transaction.php?productId=" + bookId;
		fullPage = "https://" + purchaseBaseURL + "/purchase/transaction/transaction.php?productId=" + bookId;
	} else if (page == "register") {
		// fullPage = "https://purchase.bfwpub.com/purchase/register/register.php?productId=" + bookId;
		fullPage = "https://" + purchaseBaseURL + "/purchase/register/register.php?productId=" + bookId;

	} else if (page == "custombook") {
		fullPage = "http://" + purchaseBaseURL + "/purchase/custombook/custombook.php?bookId=" + bookId;

	} else if (page == "passrem") {
		fullPage = "https://" + purchaseBaseURL + "/purchase/password_reminder/password_reminder.php";

	} else if (page == "refund") {
		fullPage = "https://" + purchaseBaseURL + "/purchase/refund.php?productId=" + bookId;

	} else if (page == "instructorreg") {
		fullPage = "https://" + purchaseBaseURL + "/purchase/instructorreg_ra.php?productId=" + bookId;

	} else if (page == "syscheck") {
		fullPage = "syscheck/index.html";
	}

	// *** special case: Henretta6e ***
	if (bookId == "henretta6e" && page == "purchase"){
		fullPage = "http://ebooks.bfwpub.com/henretta6e/henretta_bridge.html";
	}
	
	if (bookId == "physse6e" && page == "legal"){
		// KC: 8/3/2009 replaced ebooksBaseURL with urlStartBookID
		fullPage = urlStartBookID + "legal.php";
	}

	// http://bcs.bedfordstmartins.com/Login/login/loginbcs.aspx?isbn=
	
	// make sure the suppwin is in focus
	if (suppwin != null && !suppwin.closed) {
		suppwin.focus();
	}
	
	suppwin = window.open(fullPage, "loginSuppWindow", "top=20,left=20,width=800,height=620,menubar,resizable,scrollbars,status", true);	// ,location
}

// The supp window calls the following two functions upon open, thinking it
// is being opened by the textbook window.
function AddToHistory() {
	;
}

function CurrentChapter() {
	return 0;
}

function UpdateHistoryLinks() {
	// Mimic ebookAPI's KeepSuppWindowOpen function
	suppwin.banner.document.getElementById('keepopen').style.display = "none";
	suppwin.banner.document.getElementById('backvis').style.display = "none";
	suppwin.banner.document.getElementById('forwardvis').style.display = "none";
	suppwin.banner.document.getElementById('backdim').style.display = "none";
	suppwin.banner.document.getElementById('forwarddim').style.display = "none";
	suppwin.banner.document.getElementById('helpDiv').style.display = "none";
}

var showPrompt = false;
function InitializeLogin() {
	FillinUsername();

	// KT: if the account has expired, we want to make them confirm() 
	//     wether they want to renew their subscription
	// expiredAccount will be set by login.php only if the account is expired.
	if(window.expiredAccount != null && window.expiredAccount){
		ConfirmRenewAccount(bookId);
	}


	if (showPrompt && bookId != 'blah') {
		setTimeout("FadeTo('promptDiv', 85, 1000)", 1000);
	}
}


function FillinUsername() {
	var username = GetCookieVal("lfiofoe");
	if (username != null) {
		document.loginForm.username.value = username;
	}
	
	// document.loginForm.username.select();
	self.focus();	// Not sure if this is necessary, but got it from http://www.htmlgoodies.com/tabindex.html
	document.loginForm.username.focus();
}

function ConfirmRenewAccount(bookId) {
	if(confirm("Your account has expired.  You may have the option to extend your subscription to the " + bookId + " ebook for a discounted price.  Please click OK if you would like more information.")){
		purch = window.open("http://" + purchaseBaseURL + "/purchase/transaction/transaction.php?v=4&productId=" + bookId,"purch","width=630,height=450,menubar,resizable,scrollbars,status",true);
	} else {
		window.location.replace("http://ebooks.bfwpub.com/" + bookId + ".php");
	}
			
}

function StoreCookie(name, val) {
	var later = new Date();
	later.setFullYear (later.getFullYear() + 10);
	document.cookie = name + "=" + val + "; path=/; expires=" + later.toGMTString();
}

function GetCookieVal(name) {
	var cook = document.cookie;					// get the cookie
	var pos = cook.indexOf (name + '=');	// look for the named field
	if (pos != -1) {		// if found
		var start = pos + name.length + 1;
		var end = cook.indexOf(";", start);
		if (end == -1) end = cook.length;
		return cook.substring(start, end);
	} else {
		return null;
	}
}


function SetVisibility(l, v) {
	if (l != null) {
		if (v == null) {
			v = (l.style.visibility == "hidden") ? "visible" : "hidden";
		}
		l.style.visibility = v;
	}
}

function SetDisplay(l, d) {
	if (l != null) {
		if (d == null) {
			d = (l.style.display == "block") ? "none" : "block";
		}
		l.style.display = d;
	}
}

function ShowInstructorOptions() {
	SetDisplay(document.getElementById("studentOptions"), "none");
	SetDisplay(document.getElementById("instructorOptions"));
}

function ShowStudentOptions() {
	SetDisplay(document.getElementById("instructorOptions"), "none");
	SetDisplay(document.getElementById("studentOptions"));
}

// Log the user in as a guest
function Preview() {
	document.loginForm.username.value = "Guest";
	document.loginForm.password.value = "guest";
	document.loginForm.submit();
}

   //open up legal.php?bookid=$book_id&u=$username&p=$password
        //runs a query, stores that says termsaccepted
        //JS checks for cookie and redirect's according
var LegalWin;
function ShowWikiTOS(bookId) {
		
	var target = urlStartBookID + "legal.php";	
	LegalWin = window.open(target,"WH_Freeman_and_Company");

}

// AJAX functions....
var initCompleted = false;
function InitWs()
{
    if(!initCompleted)
    {
        // ui elements for network activity notification
        var CommHandlers = {
            onFailure: OnRequestFailed,
            onException: OnCommException
        }
        Ajax.Responders.register(CommHandlers)
        initCompleted = true;
    }
}

function OnRequestFailed(req, ex)
{
    alert("AJAX request failed")
    //alert(dump(req))
    alert(dump(ex))
}

function OnCommException(req, ex)
{
    alert("AJAX request exception")
    //alert(dump(req))
    alert(dump(ex))
}

function CallWs(url)
{
    InitWs();

    var dl = new Ajax.Request(
       url, 
       {
           method: 'get', 
           asynchronous: false
       })
    return dl.transport.responseText;
}

function DoTermsInsert(accept){
	// KT This url can't decide if it should be called relative to bookId/ or ebooks.bfwpub.com/
	//MPW added absolute URL
        var url = "http://" + window.location.host + "/" +  bookId + "/legal.php?cmd=insertToTerms&bookId=" + bookId + "&u=" + document.loginForm.username.value + "&p=" + document.loginForm.password.value + "&a=" + accept;
        //var url = bookId + "/legal.php?cmd=insertToTerms&bookId=" + bookId + "&u=" + document.loginForm.username.value + "&p=" + document.loginForm.password.value + "&a=" + accept;
	//mpw added try/catch block
	var ws;
	try
	{
	ws = CallWs(url);
	}
	catch(err)
	{	
	 txt="There was an error on this page.\n\n";
	 txt+="Error Description: " + err.description + "\n\n";
	 alert(txt);
	}
	
	// returns 1 but we don't care...

// debug:
//	alert(ws);
}

function AcceptTerms(){
	DoTermsInsert(1);

//	document.cookie = bookId + "_legal=1; path=/";	

	LegalWin.close();

	document.loginForm.submit();
}

function DeclineTerms(){
	DoTermsInsert(0);

	LegalWin.close();
}

function GetTerms(){
        var url = bookId + "/legal.php?cmd=getTerms&bookId=" + bookId + "&u=" + document.loginForm.username.value + "&p=" + document.loginForm.password.value;

	var ws = CallWs(url);

//alert(ws);

	// if they have not accepted then we assume they have declined
	if(ws != 1){
		ws = 0;
	}

	return ws;	

}
