/**
* The LoyaltyCardUI class
* Will handle, display and window creation for LoyaltyCard managment
*/

function LoyaltyCardUI(modelObj, listEleId, windowManager){
	this.model = modelObj;
	this.listEleId = listEleId;
	this.windowManager = windowManager;
	this.addCardFormWindowHandle = false;
	this.addCardSuccessWindowHandle = false;
	this.inSubmit = false;
	
	wm = this.windowManager;
	lcui = this;
}

LoyaltyCardUI.prototype.showAddCardFormWindow = function(merchantId, offerId, successCallback){
	var card = this.model.loyaltyCards[merchantId]; 
	
	if(card.addCardFormWindowHandle){
		var offerInput = document.getElementById("add_card_offer_"+merchantId);
		offerInput.value = offerId;
		var topTitle = document.getElementById("add_card_error_"+merchantId);
		removeChildElements(topTitle);
		topTitle.appendChild(document.createTextNode("We were unable to find your card account. Check the number and try again. New card holders: it can take up to 5 business days before your card account can be accessed."));
		topTitle.className = "error";
		this.windowManager.showWindow(card.addCardFormWindowHandle);
		return;
	}
	
	var addCardForm = this.buildAddCardForm(merchantId, false);
	
	
	card.successCallback = successCallback;
	card.addCardFormWindowHandle = this.windowManager.createNewBlackOutWindow(addCardForm, 400, 0, 0, true);
	
	// Put the offerId into the form
	var offerInput = document.getElementById("add_card_offer_"+merchantId);
	offerInput.value = offerId;
	
	this.windowManager.showWindow(card.addCardFormWindowHandle);
}

LoyaltyCardUI.prototype.showUpdateCardFormWindow = function(merchantId, successCallback)
{
	var card = this.model.loyaltyCards[merchantId]; 
	
	if(!card.addCardFormWindowHandle)
	{
		var addCardForm = this.buildAddCardForm(merchantId, true);
		card.successCallback = successCallback;
		card.addCardFormWindowHandle = this.windowManager.createNewBlackOutWindow(addCardForm, 400, 0, 0, true);
	}
	
	var topTitle = document.getElementById("add_card_error_"+merchantId);
	removeChildElements(topTitle);
	topTitle.appendChild(document.createTextNode("Are you sure you want to change your " + card.merchantName + " " + card.cardName + "?"));
	// topTitle.className = "error";
	topTitle.style.fontWeight = "normal";
	topTitle.style.fontSize = "12px";
	topTitle.style.color = "#000000";
	var ttSecond = document.createElement("span");
	topTitle.appendChild(ttSecond);
	ttSecond.style.fontWeight = "bold";
	ttSecond.appendChild(document.createTextNode(" You will lose all offers that are saved to your card."));
	
	var existingCardNum = document.getElementById("lc_number_" + merchantId);
	if (existingCardNum)
	{
		existingCardNum.value = card.cardNum;
	}	

	this.windowManager.showWindow(card.addCardFormWindowHandle);
}

LoyaltyCardUI.prototype.buildAddCardForm = function(merchantId, doUpdate)
{
	var mid = merchantId;
	var card = this.model.loyaltyCards[merchantId];

	var hasAlt = card.alternateTitle.length > 0;	
	
	var anotherCont = document.createElement("div");
	
	var cont = document.createElement('div');
	cont.id = "add_card_cont_"+mid;
	var top = document.createElement('div');
	top.id = "add_card_top_"+mid;
	var body = document.createElement('div');
	body.id = "add_card_elements_"+mid;
	
	/*
	var error = document.createElement('div');
	error.id = "add_card_error_"+mid;
	error.className = "error";
	error.style.height = "50px";
	error.style.textAlign = "left";
	error.style.margin = "0px 10px 6px 10px";
	var topText = document.createTextNode("");
	error.appendChild(topText);
	*/

	var offerInput = document.createElement("input");
	offerInput.id = "add_card_offer_"+merchantId;
	offerInput.type = "hidden";
	cont.appendChild(offerInput);
	
	if (doUpdate)
	{
		var updateInput = document.createElement("input");
		updateInput.id = "update_card_"+merchantId;
		updateInput.type = "hidden";
		updateInput.value = "1";
		cont.appendChild(updateInput);
	}
	
	var newWord = "";

	var title = document.createElement("div");
	title.style.fontSize = "18px";
	title.style.fontWeight = "bold";
	title.style.color = "black";
	if (doUpdate)
	{
		title.appendChild(document.createTextNode("Update your "+card.merchantName+" "+card.cardName));
		newWord = " New";
	}
	else
	{
		title.appendChild(document.createTextNode("Add your "+card.merchantName+" "+card.cardName));
	}	
	
	top.appendChild(title);
	
	var image_holder = document.createElement('div');
	image_holder.style.cssFloat = "left";
	image_holder.style.styleFloat = "left";
	image_holder.style.width = "100px";
	image_holder.style.height = "60px";
	image_holder.style.margin = "5px 10px 10px 10px";
	var image = document.createElement('img');
	image.src = "/images/"+card.frontImageId+".jpg";
	image_holder.appendChild(image);
	top.appendChild(image_holder);
	
	var topTitle = document.createElement("div");
	topTitle.style.height = "50px";
	topTitle.style.fontSize = "12px";
	topTitle.id = "add_card_error_"+mid;
	if(card.status <= 2)
		topTitle.appendChild(document.createTextNode("Coupons you save to your card are automatically applied when you use your card at checkout!"));
	else
		topTitle.appendChild(document.createTextNode("We were unable to find your card account. Check the number and try again. New card holders: it can take up to 5 business days before your card account can be accessed."));
	
	top.appendChild(topTitle);
	top.appendChild(document.createElement("br"));
	//top.appendChild(topText);
	var clear = document.createElement("div"); clear.className = "clear"; clear.style.height = "5px";
	top.appendChild(clear);

	var cardNum_holder = document.createElement("div");
	cardNum_holder.style.cssFloat = "left";
	cardNum_holder.style.styleFloat = "left";
	cardNum_holder.style.width = "40%";
	var cardNum_label = document.createElement("span");
	cardNum_label.style.fontSize = "12px";
	cardNum_label.style.fontWeight = "bold";
	cardNum_label.appendChild(document.createTextNode("Enter" + newWord + " Card Number"));
	cardNum_holder.appendChild(cardNum_label);
	cardNum_holder.appendChild(document.createElement("br"));
	var cardNum_input = document.createElement("input")
	cardNum_input.type = "text";
	cardNum_input.size = "12";
	cardNum_input.name = "lc_number_"+mid;
	cardNum_input.id = "lc_number_"+mid;
	cardNum_input.onkeypress = new Function("event",""+
		"var code;"+
		"if(window.event)"+
			"code = window.event.keyCode;"+
		"else if(event.which)"+
			"code = event.which;"+
		"if(code == 13)" +
			"lcui.submitAddCardForm("+mid+");");
	
	cardNum_holder.appendChild(cardNum_input);
	cardNum_holder.appendChild(document.createElement('br'));
	
	var or_holder = document.createElement('div');
	or_holder.style.width = "10%";
	or_holder.style.fontSize = "12px";
	or_holder.style.fontWeight = "bold";
	or_holder.style.cssFloat = "left";
	or_holder.style.styleFloat = "left";
	or_holder.style.color = "black";
	or_holder.style.textAlign = "center";
	or_holder.appendChild(document.createElement("br"));
	or_holder.appendChild(document.createTextNode("OR"));
	
	
	if (hasAlt)
	{
		var altNum_holder = document.createElement("div");
		altNum_holder.style.cssFloat = "right";
		altNum_holder.style.styleFloat = "right";
		altNum_holder.style.width = "50%";
		var altNum_label = document.createElement("span");
		altNum_label.style.fontSize = "12px";
		altNum_label.style.fontWeight = "bold";
		altNum_label.appendChild(document.createTextNode("Associated "+card.alternateTitle));
		altNum_holder.appendChild(altNum_label);
		altNum_holder.appendChild(document.createElement("br"));
		var altNum_input = document.createElement("input");
		altNum_input.type = "text";
		altNum_input.size = "13";
		altNum_input.name = "lc_alt_"+mid;
		altNum_input.id = "lc_alt_"+mid;
		altNum_input.onkeypress = new Function("event",""+
			"var code;"+
			"if(window.event)"+
				"code = window.event.keyCode;"+
			"else if(event.which)"+
				"code = event.which;"+
			"if(code == 13)" +
				"lcui.submitAddCardForm("+mid+");");
		altNum_holder.appendChild(altNum_input);
	}	
	else
	{
		var noAlt_holder = document.createElement("div");
		noAlt_holder.style.width = "50%";
		noAlt_holder.style.cssFloat = "right";
		noAlt_holder.style.styleFloat = "right";
		var altNum_input = document.createElement("input");
		altNum_input.type = "hidden";
		altNum_input.value = "";
		altNum_input.name = "lc_alt_"+mid;
		altNum_input.id = "lc_alt_"+mid;
		noAlt_holder.appendChild(altNum_input);
		var noAltMessage = document.createElement("div");
		if (doUpdate)
		{
			noAltMessage.innerHTML = "";
		}
		else
		{
			noAltMessage.innerHTML = card.supportHTML;
		}	
		noAlt_holder.appendChild(noAltMessage);
	}	
	
	var  buttonAlign = "left";
	if (hasAlt)
	{
		buttonAlign = "right";
	}	
	
	var button_holder = document.createElement("div");
	button_holder.style.textAlign = "right";
	var button;
	if (this.model.inIframe)
	{
		button = document.createElement("div");
		button.style.margin = "5px 0px 0px 0px";
		button.style.height = "25px";
		var buttonImg = document.createElement("img");
		buttonImg.onclick = new Function("lcui.submitAddCardForm("+mid+");");
		if (doUpdate)
		{
			buttonImg.src = "/includes/templates/affiliate/" + this.model.iframeCssId + "/button_updatecard.png";
			buttonImg.alt = "Update Card";
		}
		else
		{
			buttonImg.src = "/includes/templates/affiliate/" + this.model.iframeCssId + "/button_addcard.jpg";
			buttonImg.alt = "Add Card";
		}
		buttonImg.style.cursor = "pointer";
		button.appendChild(buttonImg);
	}
	else
	{
		button_holder.appendChild(document.createElement("br"));
		button = getButton("blue","Add Card", 80, new Function("lcui.submitAddCardForm("+mid+");"));
	}	
	button.style.cssFloat = buttonAlign;
	button.style.styleFloat = buttonAlign;
	
	button_holder.appendChild(button);
	
	var clear = document.createElement("div");
	clear.className = "clear";
	button_holder.appendChild(clear);
	
	
	body.appendChild(cardNum_holder);
	if (hasAlt)
	{
		body.appendChild(or_holder);
		altNum_holder.appendChild(button_holder);
		body.appendChild(altNum_holder);
	}
	else
	{
		body.appendChild(noAlt_holder);
		cardNum_holder.appendChild(button_holder);
	}	
	
	var clear = document.createElement("div"); clear.className = "clear";
	body.appendChild(clear);
	cont.appendChild(top);
	// cont.appendChild(error);
	cont.appendChild(body);
	var anotherClear = document.createElement("div");
	anotherClear.className = "clear";
	cont.appendChild(anotherClear);
	
	return cont;
}

LoyaltyCardUI.prototype.showAddCardSuccessWindow = function(merchantId, offerCount){
	var card = this.model.loyaltyCards[merchantId];
	
	if(card.addCardSuccessWindowHandle){
		this.windowManager.showWindow(card.addCardSuccessWindowHandle);
		return;
	}
	
	var addCardSuccess = this.buildAddCardSuccess(merchantId, offerCount);
	card.addCardSuccessWindowHandle = this.windowManager.createNewBlackOutWindow(addCardSuccess, 350, 0, 0, true);
	
	this.windowManager.showWindow(card.addCardSuccessWindowHandle);
}

LoyaltyCardUI.prototype.buildAddCardSuccess = function(merchantId, offerCount){
	var card = this.model.loyaltyCards[merchantId];
	
	var success = document.createElement('div');
	success.id = "add_card_success_"+merchantId;

	var title = document.createElement("div");
	title.style.fontSize = "16px";
	title.style.color = "black";
	title.style.fontWeight = "bold";
	
	var titleText = "Saving Coupon to Card";
	var bodyText = "Your coupon is being saved to your " + card.merchantName + " " +  card.cardName + ". It will be available to redeem in about " + card.processTime + " minutes."
	if (offerCount > 1)
	{
		titleText = "Saving Coupons to Card";
		bodyText = "Your coupons are being saved to your " + card.merchantName + " " +  card.cardName + ". They will be available to redeem in about " + card.processTime + " minutes."	
	}
	
	title.appendChild(document.createTextNode(titleText));
	success.appendChild(title);
	success.appendChild(document.createElement("br"));
	success.appendChild(document.createTextNode(bodyText + " Just use your card at checkout to get your discount!"));
	success.appendChild(document.createElement("br"));
	success.appendChild(document.createElement("br"));
	
	var footnote = document.createElement("div");
	// footnote.style.fontWeight = "bold";
	footnote.appendChild(document.createTextNode("Click \"OK\" to continue saving coupons to your card."));
	success.appendChild(footnote);
	
	var center = document.createElement("div");
	center.style.textAlign = "center";
	center.style.margin = "10px 0px";
	success.appendChild(center);
	
	var closeButton;
	if (this.model.inIframe)
	{
		closeButton = document.createElement("div");
		closeButton.style.height = "25px";
		var closeButtonImg = document.createElement("img");
		closeButtonImg.onclick = function(){wm.closeOpenWindow()};
		closeButtonImg.src = "/includes/templates/affiliate/" + this.model.iframeCssId + "/button_ok.jpg";
		closeButtonImg.style.cursor = "pointer";
		closeButtonImg.alt = "OK";
		closeButton.appendChild(closeButtonImg);
	}	
	else
	{
		var buttonOnClick = function(){wm.closeOpenWindow()};
		closeButton = getButton("blue","OK", 50, buttonOnClick);
		closeButton.style.margin = "auto";
	}	
	center.appendChild(closeButton);
	var cDiv = document.createElement("div");
	cDiv.className = "clear";
	center.appendChild(cDiv);
	
	return success;
}

LoyaltyCardUI.prototype.successOKCallback = function(merchantId){
	var card = this.model.loyaltyCards[merchantId];
	this.windowManager.hideWindow(card.addCardSuccessWindowHandle);
}

LoyaltyCardUI.prototype.submitAddCardForm = function(merchantId){
	var offerIdInput = document.getElementById("add_card_offer_"+merchantId);
	var offerId = offerIdInput?offerIdInput.value:false;
	var doingAssoc = this.model.isOfferAssocOffer(offerId);
	
	var updateFlag = document.getElementById("update_card_" + merchantId);
	var doingUpdate = (updateFlag && updateFlag.value == "1");
	var error = document.getElementById("add_card_error_"+merchantId);
	error.className = "error";
	removeChildElements(error);
	
	var loader_img = document.createElement("img");
	//if(!loader_img) alert("loader image no good");
	loader_img.src="/includes/templates/master/images/loader.gif";
	error.appendChild(loader_img);
	if(lcui.validateAddCardForm(merchantId))
		this.postAddCardForm(merchantId, offerId, doingAssoc, doingUpdate);
	else{
		removeChildElements(error);
		error.appendChild(document.createTextNode("I'm sorry, that is an invalid card number. Please try again."));
	}
}

LoyaltyCardUI.prototype.cancelAddCardForm = function(merchantId){
	//var error = document.getElementById("add_card_error_"+merchantId);
	//removeChildElements(error);
	this.windowManager.hideWindow(this.model.loyaltyCards[merchantId].addCardFormWindowHandle);
}

LoyaltyCardUI.prototype.validateAddCardForm = function(merchantId){
	//alert("validateAddCardForm not implemented");
	return true;
}

LoyaltyCardUI.prototype.postAddCardForm = function(mid, offerId, doingAssoc, doingUpdate){
	if (!this.inSubmit)
	{
		customPageTracker('add_card_popup_attempt');
		var notAddingOffer = (offerId == false);
		var req = getXMLHttpObject();
		req.onreadystatechange = function(){
			if(req.readyState == 4){
				var callback = new Function("lcui.onAddCardCallback("+mid+","+req.responseText+", " + notAddingOffer + ")");
				callback();
			}
		}

		var cardNum = document.getElementById("lc_number_"+mid).value;
		var altNum = document.getElementById("lc_alt_"+mid).value;
		var openString = "/includes/form_handlers/loyalty.php?mid="+mid+"&offer="+offerId+"&cnum="+cardNum+"&altnum="+altNum + "&doingAssoc=" + doingAssoc + "&doingUpdate=" + doingUpdate;

		req.open("GET",openString,true);
		req.send(null);
		this.inSubmit = true;
	}	
}

LoyaltyCardUI.prototype.onAddCardCallback = function(merchantId, code, dontShowOKBox){
	this.inSubmit = false;
	var error = document.getElementById("add_card_error_"+merchantId);
	error.className = "error";
	removeChildElements(error);
	
	var card = this.model.loyaltyCards[merchantId]; //if(!card) alert("onAddCardCallback card not found"); 
	var pleaseEnter; 
	if (card && card.alternateTitle.length > 0)
	{
		pleaseEnter =  "lease enter the " + card.cardName + " number or the " + card.alternateTitle + " that is associated with your card.";
	}
	else
	{
		pleaseEnter =  "lease enter the " + card.cardName + " number that is associated with your card.";
	}	
	
	// alert("onAddCardCallback - merchantId = " + merchantId + " code = " + code + " dontShowOKBox = " + dontShowOKBox);
		
	if(code == 1){ // Success
		
		var newCard;
		var cardNumInput = document.getElementById("lc_number_"+merchantId); 
		var altNumInput = document.getElementById("lc_alt_"+merchantId);
		var offerId = document.getElementById("add_card_offer_"+merchantId).value;
				
		if(!card.successCallback);// alert("addCardCallback card has no callback function");
		else card.successCallback();
		
		this.model.updateLoyaltyCard(merchantId, cardNumInput.value, altNumInput.value, 2, offerId);
		if (!dontShowOKBox)
		{
			this.showAddCardSuccessWindow(merchantId, 1);
		}	
		else
		{
			this.windowManager.hideWindow(this.model.loyaltyCards[merchantId].addCardFormWindowHandle);
		}	
	}
	else if(code == 2){ // already in use
		customPageTracker('add_card_error_already_in_use');
		error.appendChild(document.createTextNode("We're sorry, but that card is already assigned to another " + this.model.clientName + " account. Please check the number and try again or click "));
		var link = document.createElement("a");
		link.href = "javascript: window.location=document.location.pathname + '?faq=1&faq_q=qCardInUse#qCardInUse'";
		link.appendChild(document.createTextNode("here"));
		error.appendChild(link);
		error.appendChild(document.createTextNode(" to learn why you might be getting this message."));
	}
	else if(code == 3){ // Checksum failed
		customPageTracker('add_card_error_checksum');
		error.appendChild(document.createTextNode("Sorry, that is not a valid number, p" + pleaseEnter));
	}
	else if(code == 4){ // Empty fields
		customPageTracker('add_card_error_missing_values');
		error.appendChild(document.createTextNode("P" + pleaseEnter));
	}
	else if(code == -2){ // Remove failed 'cos offers are pending
		customPageTracker('add_card_error_update_remove_error');
		error.appendChild(document.createTextNode("You currently have coupons that are in the process of being saved to your card. Please wait a few minutes before trying to remove your card."));
	}	
	else
	{
		error.appendChild(document.createTextNode("We are currently having technical difficulties, please try again soon. Error("+code+")"));
	}
}

LoyaltyCardUI.prototype.showSavingsHistory = function(merchantId){
	var card = this.model.loyaltyCards[merchantId];
	if(!card || card.status != 2) return;
	
	if(card.savingsHistoryWindowHandle){
		this.windowManager.showWindow(card.savingsHistoryWindowHandle);
		return;
	}
	
	var saveHistory = this.buildSavingsHistory(merchantId);
	card.savingsHistoryWindowHandle = this.windowManager.createNewBlackOutWindow(saveHistory, 500, 0, 0, true);
	this.windowManager.showWindow(card.savingsHistoryWindowHandle);
}

LoyaltyCardUI.prototype.buildSavingsHistory = function(merchantId){
	var holder = document.createElement('div');
	holder.style.width = "100%";
	holder.style.position = "relative";
	
	var card = this.model.loyaltyCards[merchantId];
	if(!card) return holder;
	
	var content = document.createElement('div');
	content.style.padding = "10px";
	//content.style.position = "relative";
	content.style.display = "inline-block";
	holder.appendChild(content);
	
	var title = document.createElement('div');
	title.style.position = "relative";
	title.style.width = "100%";
	title.style.borderBottom = "1px solid #666666";
	//title.style.height = "30px";
	//title.style.top = "0";
	//title.style.left = "0";
	title.style.fontSize = "32px";
	content.appendChild(title);
	
	var logo = document.createElement('img');
	logo.src = "/images/"+card.frontImageId+".jpg";
	logo.style.width = "60px";
	logo.style.height = "36px";
	logo.style.margin = "0px 3px 0px 0px";
	title.appendChild(logo);

	/*
	var titleBack = document.createElement('div');
	titleBack.className = "locationLogoBack";
	//title.appendChild(titleBack);
	*/
	
	var titleText = document.createElement('div');
	title.appendChild(document.createTextNode(card.merchantName+" "+card.cardName));
	titleText.style.position = "relative";
	titleText.style.zIndex = "100";
	titleText.style.display = "inline-block";
	//title.appendChild(titleText);
	
	var table = document.createElement('table');
	table.style.width = "100%";
	content.appendChild(table);
	
	var row = document.createElement('tr');
	table.appendChild(row);
	var date = document.createElement('th');
	date.appendChild(document.createTextNode("Date"));
	row.appendChild(date);
	var description = document.createElement('th');
	description.appendChild(document.createTextNode("Description"));
	row.appendChild(description);
	var savings = document.createElement('th');
	savings.appendChild(document.createTextNode("Savings"));
	row.appendChild(savings);
	
	for(var i in card.history){
		var trans = card.history[i];
		if(!trans) continue;
		var row = document.createElement('tr');
		table.appendChild(row);
		var date = document.createElement('td');
		date.appendChild(document.createTextNode(trans.transactionTime));
		row.appendChild(date);
		var description = document.createElement('td');
		description.appendChild(document.createTextNode(trans.couponName));
		row.appendChild(description);
		var savings = document.createElement('td');
		savings.appendChild(document.createTextNode("$"+trans.saving));
		row.appendChild(savings);
	}
	
	return holder;
}
