var jQ = jQuery.noConflict();

checkForApaSession();

function addHyperlink(elementId, addHtml) {
	jQ(elementId).prepend(addHtml);
}

function getCookie(cookie_name){
	var value = YAHOO.util.Cookie.get(cookie_name);
	return value;
}

function hasCookie(cookieName){
    return getCookie(cookieName) != null;
}

function setCookie(cookieName, cookieValue){
	YAHOO.util.Cookie.set(cookieName, cookieValue); 
}

function setLoggedInUserName(name){
	addHyperlink("#HeaderLoggedInLink","<a disabled='true' href='#'>" + name + "</a>");
}

function setLoginLink() {
	var erightsReturnParam = "?ERIGHTS_TARGET=";
	addHyperlink("#HeaderLoginLink", "<a href='" + myApaUrl
			+ "/apa/idm/login.seam" + erightsReturnParam + location.href
			+ "' target='_parent'>Log In</a>");
}

function setLogoutLink() {
	var logoutUrl = myApaUrl + "/portal/signout?location=/apa/idm/logout.seam";
	var erightsReturnParam = "?ERIGHTS_TARGET=";
	addHyperlink("#HeaderLogoutLink", "<a href='" + logoutUrl
			+ erightsReturnParam + location.href
			+ "' target='_parent'>Log Out</a>");
}

function setMyApaLink() {
	addHyperlink("#HeaderMyApaLink", "<a href='" + myApaUrl + "/portal' target='_parent'>MyAPA</a> | ");
}

function updateShoppingCart(quantity, totalPrice) {
	if (quantity) {
		var cartText = "(" + quantity + " Items)";
		if (quantity < 2) {
			cartText = "(" + quantity + " Item)";
		}
		jQ("#CartQuantity").html(cartText);
	}
	if (totalPrice) {
		jQ("#CartPrice").html(totalPrice);
	}
}

function addHtmlAtEndOfBody(htmlString) {
	var bodyChildren = jQ('body').children();
	var lastChild = bodyChildren.get(bodyChildren.length - 1);
	var iframeObject = jQ(htmlString);
	jQ(lastChild).after(iframeObject);
}

function createIframe() {
//	if(hasCookie("ERIGHTS")) {
	if(hasCookie("JSESSIONID")) {
		addHtmlAtEndOfBody('<iframe id="apaAuthIframe" src="/apa_core/idm/userIdentity.seam" height="0" width="0" frameborder="0"></iframe>');
	//	alert('Creating iFrame' + iFrameHtml);
	}
}

function createShopIframe() {
	//alert("SessionKey:" + getCookie("apaSessionKey"));
	//addHtmlAtEndOfBody('<iframe id="shoppingIframe" src="/apa_core/shop/cartFrame.seam;jsessionid=' + getCookie("apaSessionKey") + ' width="0" height="0" frameborder="no"></iframe>');
	addHtmlAtEndOfBody('<iframe id="shoppingIframe" src="/apa_core/shop/cartFrameXDomain.html" width="0" height="0" frameborder="no"></iframe>');
}

function checkForApaSession() {
	// use Yahoo cookie utility to check for a a cookie named apaSessionKey
	// The apaSessionKey is actually the jsessionid when the user hits the
	// shopping cart page on ____.apa.org.
	// If the cookie is not present then check for a url redirect the user to
	// 'myApaUrl + "/apa/idm/getSessionId'
	//var apaSessionKey = "apaSessionKey";
	var apaSessionKey = "apaSessionKey";

	//alert("In before hascookie");
	if(!hasCookie("JSESSIONID")) {
		// see
		// http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2
		// for getUrlParam - added script to apaAuthIframe.js
		// document.location=myApaUrl +
		// "/apa/idm/getSessionId.seam?REDIRECT_TARGET=" + document.location;
		// alert(document.location);
		var apaUrlParam = jQ(document).getUrlParam(apaSessionKey);
		//alert("apaUrlParam:" + apaUrlParam);
		//var apaUrlParam = gup(apaSessionKey);
		if(apaUrlParam != null ) {
			YAHOO.util.Cookie.set("JSESSIONID", apaUrlParam, {path: "/"});
			// Reloading the page without the URL Parameter
			var loc = decodeURI(window.location);
			var reloadLoc = loc.substring(0, loc.indexOf('?'));
			if (reloadLoc != "") window.location.href = reloadLoc;
		}
		else {
			document.location=myApaUrl + "/apa/idm/getSessionId.seam?REDIRECT_TARGET=" + encodeURIComponent(document.location);
		}
	}
	else {
	}
}

function loadApaIdm() {
	try {
		myApaUrl;
//		alert("myapaUrl: " + myApaUrl);
	} catch (err) {
//		alert("in catch");
		myApaUrl = undefined;
	}
	if (myApaUrl == undefined) {
		myApaUrl = 'http://mydev4.apa.org';
	}
	var userName = jQ('#apaAuthIframe').contents().find('#userName').text();
//	alert('userName is ' + userName);
	if (hasCookie("JSESSIONID") && (userName != 'false')) {
	//if (hasCookie("ERIGHTS") && (userName != 'false')) {
		setLogoutLink();
		setMyApaLink();
		setLoggedInUserName(userName);
	} else {
		setLoginLink();
	}
//	alert("successfull execution of the function.");
	
	// Checking for erights cookie, If present, refreshing the session and if not present creating one.
	var erightsCookieValue = getCookie("ERIGHTS");
	if (erightsCookieValue != null) {
		document.getElementById('shoppingIframe').contentWindow.refreshErightsSession(erightsCookieValue);
	}
	else {
		document.getElementById('shoppingIframe').contentWindow.getErightsSessioinId();
	}
}

window.onload = loadApaIdm;

// This function is called by the cartFrameXDomain.html:refreshErightsSession()
function refreshErightsCookieResponse(response) {
	if (response == false || response == "false") {
		YAHOO.util.Cookie.remove("ERIGHTS");
	}
}


//function showOverlay() {jQ("<div id='overlay'><div id='overlayImage'><div class='waitText'>Please Wait...</div></div>").appendTo("body");}
function showOverlay() {
	jQ("<div id='overlay'></div><div id='overlayImage'><img src='/apa_core/shop/img/ajax.gif' /><div class='waitText'>Please Wait...</div></div>").appendTo("body");
	jQ("#overlay").css("width", jQ(document).width());
	jQ("#overlay").css("height", jQ(document).height());
}

function hideOverlay() {jQ("#overlay").remove();jQ("#overlayImage").remove();}

function showActiveLicenseOverlay() {
	showOverlay();
	jQ("<div class='activeLicenseDiv'><div class='notLoggedInWindowClose'>" +
			"<a href='#' onclick='javascript:hideActiveLicenseDiv()'>Close <img src='/apa_core/shop/img/close-window-icon.gif' /></a></div>" +
			"<div class='notLoggedInForm'>" +
			"<h2>Sorry, we can't add this item to your cart.</h2>" +
			"<p class='notLoggedInDivP'>You already have an active license on this product.</p>" +
			"</div></div>").appendTo("body");
}

function hideActiveLicenseDiv(reloadPage) {
	hideOverlay();
	jQ(".activeLicenseDiv").remove();
}

function showLogInOverlay() {
	showOverlay();
	jQ("<div class='notLoggedInDiv'>" +
			"<div class='notLoggedInWindowClose'>" + 
				"<a href='#' onclick='javascript:hideLogInOverlay()'>Close <img src='/apa_core/shop/img/close-window-icon.gif' /></a></div>" +
				"<div class='notLoggedInForm'><h2>Sorry, we can't add this item to your cart.</h2>" +
					"<p class='notLoggedInDivP'>You must <a href='#' onclick='login()'>log in</a> to your APA account to add this item to your cart.</p>" +
						"<p class='notLoggedInDivP' id='loginLink'>" +
						"Some CE products can only be bought every 6 months, and we'll verify you are eligible to purchase this product. <br />" +
						"Don't have an account? <a href='#' onclick='register()'>Create your account</a>.</p></div></div>").appendTo("body");
}

function hideLogInOverlay() {hideOverlay();jQ(".notLoggedInDiv").remove();}

function showNotMemberOverlay() {
	showLogInOverlay();
	jQ("#loginLink").remove();
	jQ(".notLoggedInButton").remove();
}

function showOutOfQuantityOverlay() {
	showOverlay();
	jQ("<div class='activeLicenseDiv'><div class='notLoggedInWindowClose'>" +
			"<a href='#' onclick='javascript:hideActiveLicenseDiv(true)'>Close <img src='/apa_core/shop/img/close-window-icon.gif' /></a></div>" +
			"<div class='notLoggedInForm'>" +
			"<h2>Sorry, we do not have the quantity you requested.</h2>" +
			"<p class='notLoggedInDivP'>We are updating your cart with the maximum quantity available.</p>" +
			"</div></div>").appendTo("body");
}

function showNoMoreQuantityAllowedInCart() {
	showOverlay();
	jQ("<div class='notLoggedInDiv'>" +
			"<div class='notLoggedInWindowClose'>" + 
				"<a href='#' onclick='javascript:hideLogInOverlay()'>Close <img src='/apa_core/shop/img/close-window-icon.gif' /></a></div>" +
				"<div class='notLoggedInForm'><h2>Sorry, we can't add this item to your cart.</h2>" +
					"<p class='notLoggedInDivP'>This item may only be purchased in single quantities.</p>" +
						"<p class='notLoggedInDivP' id='loginLink'>" +
						"You may, however, purchase other similar items.</p></div></div>").appendTo("body");
}

function login() {
	window.location.href = "/apa_core/idm/login.seam?ERIGHTS_TARGET=" + location.href;    
}

function register() {
	window.location.href = "/apa_core/idm/register.seam?ERIGHTS_TARGET=" + location.href;
}

function addItemToCart(itemId, quantity){
	// alert("In iframe called addItemToCart("+itemId+", " + quantity + ")");
	document.getElementById('shoppingIframe').contentWindow.addItemToCart(itemId, quantity);
}