YAHOO.namespace("gl");

/* Stealing the single most useful thing in the Prototype library.
 * This function allows you to explicitly bind the scope of the "this"
 * reference. The default behavior of JavaScript if you assign a function from
 * an object to another object, for example an event handler of a DOM element,
 * is for the "this" reference within the function to refer to the new owner.
 * Using this function allows you to bind the this reference to the original
 * object.
 */
Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
};

/*
 * This function submits an ATG form via AJAX. It fakes x and y coordinates
 * of the image input specified to simulate an actual click, so the ATG
 * server will properly process the form.
 * Params:
 * formName: name of the form to submit
 * imageName: name of the image input to submit the form
 * callback: a JavaScript object suitable for call into YAHOO.util.Connect.asyncRequest.
 * At minimum this should contain success and failure properties, which should be 
 * functions to handle the response from the server.  For more info see
 * http://developer.yahoo.com/yui/connection/
 */
function submitATGImageFormAsync(formName, imageName, callback) {
	var form = document.forms[formName];
	var imageArr;
	if (form) {
		imageArr = YAHOO.util.Dom.getElementsBy(function(node) {
			return node.name == imageName;	
		}, 'input', form);
	}
	if (form && imageArr && imageArr[0]) {
		/* create fake image click data so form handler method will be invoked */
		var imageClickData = imageName + ".x=1&" + imageName + ".y=1" ; 
		
		YAHOO.util.Connect.setForm(form);
		YAHOO.util.Connect.asyncRequest(form.method, form.action, callback, imageClickData);
	}
}

/*
 * Submits an ATG form via AJAX. To use this you should declare a hidden field in the form
 * tied to the form handler method.
 * Params:
 * formName: name of the form to submit
 * callback: a JavaScript object suitable for call into YAHOO.util.Connect.asyncRequest.
 * At minimum this should contain success and failure properties, which should be 
 * functions to handle the response from the server.  For more info see
 * http://developer.yahoo.com/yui/connection/
 */
function submitATGFormAsync(formName, callback) {
	var form = document.forms[formName];

	if (form) {
		YAHOO.util.Connect.setForm(form);
		YAHOO.util.Connect.asyncRequest(form.method, form.action, callback);
	}
}

function imbedSessionId(anchor) {
  var pos = document.cookie.indexOf('JSESSIONID=');
  if (pos != -1) {
	  var valStart = pos + 11;
	  var valEnd = document.cookie.indexOf(';', valStart);
	  if (valEnd == -1) valEnd = document.cookie.length;
	  var val = document.cookie.substring(valStart, valEnd);
	  var hrefUrl = anchor.href;
	  var qPos = hrefUrl.indexOf('?');
	  if (qPos == -1) {
		qPos = hrefUrl.length; 
	  }
	  var newUrl = hrefUrl.substring(0, qPos);
	  newUrl = newUrl + ';jsessionid=' + val;
	  if (qPos != hrefUrl.length) {
		newUrl = newUrl + hrefUrl.substring(qPos);
	  }
	  anchor.href = newUrl;
  }
  return true;
}

function launchPlayer(url, params) {
	var wn;
	wn = window.open(url, "embPlayer", "resizable=no,height=678,width=952,scrollbars=0,location=0,menubar=0,toolbar=0");
	wn.focus();
	var evt = YAHOO.util.Event.getEvent();
	YAHOO.util.Event.stopEvent(evt);
}

/*
 * Resize a window so the client area is the specified dimensions.
 */
function resizeInner(width, height) {
	window.resizeTo(width, height);
	var diffw = width - YAHOO.util.Dom.getViewportWidth();
	var diffy = height - YAHOO.util.Dom.getViewportHeight();
	window.resizeTo(width + diffw, height + diffy);
}

/*
 * http://www.htmlcodetutorial.com/linking/linking_famsupp_75.html
 * 8987: remove focus on mylink page
 */
function targetopener(mylink, closeme, closeonly) {
    if (typeof window.opener != 'undefined' && window.opener && !window.opener.closed) {
		if (!closeonly) {
		    window.opener.location.href=mylink.href;
		}
		if (closeme) {
		    window.close();
		}
		return false;
    } else {
		var wn = window.open(mylink);
		if (closeme) {
		    window.close();
		}
		return false;
    }
}

function elementExpand(expandElementID, linkElementID, expandText, collapseText) {
	var expandElement = document.getElementById(expandElementID);
	var linkElement = document.getElementById(linkElementID);
	
	if( expandElement.style.display ) {
		if( expandElement.style.display == "inline" || expandElement.style.visibility == "visible" ) {
			expandElement.style.display = "none";
			expandElement.style.visibility = "hidden";
			if (linkElement && expandText) {
				linkElement.innerHTML = expandText;
			}
		} else {
			expandElement.style.display = "inline";
			expandElement.style.visibility = "visible";
			if (linkElement && collapseText) {
				linkElement.innerHTML = collapseText;
			}
		}
	}
}

/* These two functions work around an issue in Firefox where colors applied to <option> elements
 * will not propogate up to the containing <select>.  To use it simply include a call to
 * YAHOO.util.Event.onDOMReady(fixSelectColors, "elId") in the page, where "elId" is the ID of the 
 * <select> dropdown.
 */
function updateSelectColors() {
	var opt = this.options[this.selectedIndex];
	this.style.color = opt.style.color;
}

function fixSelectColors(type, args, elId) {
	var slct = document.getElementById(elId);
	if (slct) {
		var idx = slct.selectedIndex;
		var opt = slct.options[idx];
		var clr = opt.style.color;
		slct.style.color = clr;
		YAHOO.util.Event.addListener(slct, "change", updateSelectColors, null, slct);
	}
}

/* Thin control layer to allow external left/right arrow controls */
YAHOO.gl.CarouselControls = function(opts) {
	this.carousel = opts.carousel;
	this.leftButtonId = opts.leftButtonId;
	this.rightButtonId = opts.rightButtonId;
	this.leftDisabledClass = opts.leftDisabledClass;
	this.leftEnabledClass = opts.leftEnabledClass;
	this.rightDisabledClass = opts.rightDisabledClass;
	this.rightEnabledClass = opts.rightEnabledClass;
	YAHOO.util.Event.addListener(this.leftButtonId, "click", this.onLeftButtonClick, null, this);
	YAHOO.util.Event.addListener(this.rightButtonId, "click", this.onRightButtonClick, null, this);
	this.carousel.addListener("afterScroll", this.onAfterScroll, null, this);
}

YAHOO.gl.CarouselControls.prototype = {
	onLeftButtonClick: function() {
		this.carousel.scrollPageBackward();
	},
	onRightButtonClick: function() {
		this.carousel.scrollPageForward();
	},
	onAfterScroll: function(visibleItems) {
		var leftButton = document.getElementById(this.leftButtonId);
		var rightButton = document.getElementById(this.rightButtonId);
		var numItems = this.carousel.get("numItems");
		var numVisible = this.carousel.get("numVisible");
		
		if (leftButton) {
			if (visibleItems.first == 0) {
				YAHOO.util.Dom.replaceClass(leftButton, this.leftEnabledClass, this.leftDisabledClass);
			} else {
				YAHOO.util.Dom.replaceClass(leftButton, this.leftDisabledClass, this.leftEnabledClass);
			}
		}
		if (rightButton) {
			if (visibleItems.first == visibleItems.last || visibleItems.last - visibleItems.first < numVisible) {
				YAHOO.util.Dom.replaceClass(rightButton, this.rightEnabledClass, this.rightDisabledClass);
			} else {
				YAHOO.util.Dom.replaceClass(rightButton, this.rightDisabledClass, this.rightEnabledClass);
			}
		}
	}
}

/* truncates link text for links in fixed height divs.  assumes 1 link per container. */
function truncOverflowLinks(className, containerId, overflow, pMoreText) {
	var allowedOverflow = (overflow ? parseInt(overflow) : 0);
	var moreText = pMoreText || "...";
	var containers = YAHOO.util.Dom.getElementsByClassName(className, null, containerId);
	if (containers) {	
		for (var i = 0;i < containers.length; i++) {
			var links = YAHOO.util.Dom.getChildrenBy(containers[i], function(node) {
				return node.tagName == 'A';
			});
			if (links && links.length > 0) {
				var link = links[0];
				var text = link.innerHTML;
				var contHeight = containers[i].offsetHeight;
				var maxHeight = contHeight + allowedOverflow;
				while (link.offsetHeight > maxHeight) {
					var idx = text.lastIndexOf(" ");
					text = text.substr(0, idx);
					link.innerHTML = text + moreText;
				}
			}
		}
	}
}

/* these two functions are tightly coupled with the UI in /includes/merchSceneFrag.jhtml */
function addSceneMerchFrag(sceneId, showRemove) {
	var callback = {
		success: function(o) {
			var span = document.getElementById("sceneSpan" + o.argument.sceneId);
			if (showRemove) {
				var link = span.getElementsByTagName("a")[0];
				link.innerHTML = "Remove";
				link.onclick = function() {
					removeSceneMerchFrag(o.argument.sceneId);
				}	
			} else {
				span.innerHTML = "Saved";
			}
			YAHOO.namespace("gl");
			if (YAHOO.gl.postAddSceneFunc) {
				YAHOO.gl.postAddSceneFunc();
			}
		},
		failure: function(o) {},
		argument: {"sceneId": sceneId}
	};
	YAHOO.util.Connect.asyncRequest('GET', "/ajax/addOrRemoveScene.jhtml?add=" + sceneId, callback); 
	var evt = YAHOO.util.Event.getEvent();
	YAHOO.util.Event.stopEvent(evt);
}

function removeSceneMerchFrag(sceneId) {
	var callback = {
		success: function(o) {
			YAHOO.namespace("gl");
			if (YAHOO.gl.reloadOnRemoveScene) {
				window.location.reload(true);
			} else {
				var span = document.getElementById("sceneSpan" + o.argument.sceneId);
				var link = span.getElementsByTagName("a")[0];
				link.innerHTML = "Save";
				link.onclick = function() {
					addSceneMerchFrag(o.argument.sceneId);
				}
				if (YAHOO.gl.postRemoveSceneFunc) {
					YAHOO.gl.postRemoveSceneFunc();
				}
			}
		},
		failure: function(o) {},
		argument: {"sceneId": sceneId}
	};
	YAHOO.util.Connect.asyncRequest('GET', "/ajax/addOrRemoveScene.jhtml?remove=" + sceneId, callback);
	var evt = YAHOO.util.Event.getEvent();
	YAHOO.util.Event.stopEvent(evt);
}

function requestPassword() {
	var form = document.getElementById("passwordReminderForm");
	form.submit();
}

function setDefaultInputText(inputId, msg) {
	YAHOO.util.Event.onContentReady(inputId, function() {
		var input = document.getElementById(inputId);
		if (input.value == '') {
			input.value = msg;
			YAHOO.util.Event.addFocusListener(input, function() {
				if (this.value == msg) {
					this.value = '';
				}
			}, null, input);
			YAHOO.util.Event.addBlurListener(input, function() {
				if (this.value == '') {
					this.value = msg;
				}
			}, null, input);
		}
	});
}

function requestPasswordForError() {
	var callback = {
		success: function(o) {
			var result = YAHOO.lang.JSON.parse(o.responseText);
			displayPwMessageMoveBox(result.message);
			if (result.result == 'success') {
				var regForm = document.getElementById('registrationForm');
				var textFields = YAHOO.util.Dom.getElementsBy(function(el) {
					return el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'password');
				}, 'INPUT', regForm);
				for (var i = 0; i < textFields.length; i++) {
					textFields[i].value = '';
				}
				var loginForm = document.getElementById('loginForm');
				textFields = YAHOO.util.Dom.getElementsBy(function(el) {
					return el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'password');
				}, 'INPUT', loginForm);
				for (var i = 0; i < textFields.length; i++) {
					var field = textFields[i];
					if (field.type == 'text') {
						field.value = result.email;
					} else if (field.type == 'password') {
						field.focus();
					}
				}
			}
		},
		failure: function(o) {
			displayPwMessage("We encountered an error sending your password. Please try again later or contact Customer Service.");
		}
	};
	submitATGFormAsync("passwordReminderErrorForm", callback);
}

function requestPasswordForPPM() {
	var callback = {
		success: function(o) {
			var result = YAHOO.lang.JSON.parse(o.responseText);
			displayPwMessageMoveBox(result.message, 'ppmErrorBox', 'ppmLoginErrorContainer');
			updateLoginSuccessLink('/pay_per_minute.jhtml');
		},
		failure: function(o) {
			displayPwMessage("We encountered an error sending your password. Please try again later or contact Customer Service.");
		}
	};
	submitATGFormAsync("passwordReminderErrorForm", callback);
}

function updateLoginSuccessLink(successLink) {
	var login = document.getElementById('topLogin');
	
	if (login.href.indexOf('?') != -1) {
		login.href+= "&successURL=" + successLink;
	} else {
		login.href+= "?successURL=" + successLink;
	}
}

function displayPwMessage(msg) {
	var div = document.getElementById("pwResult");
	div.innerHTML = "<em>" + msg + "</em>";
	div.style.display = "block";
}

function displayPwMessageClearError(msg) {
	var div = document.getElementById("errorBox");
	div.innerHTML = '<div style="padding: 3px;"><em>' + msg + '</em></div>';
}

function displayPwMessageMoveBox(msg, errorBox, loginErrorContainer) {
	var div;
	if (errorBox) {
		div = document.getElementById(errorBox);
	} else {
		div = document.getElementById("errorBox");
	}
	var divParent = div.parentNode;
	divParent.removeChild(div);
	var loginErrorDiv;
	if (loginErrorContainer) {
		loginErrorDiv = document.getElementById(loginErrorContainer);
		loginErrorDiv.innerHTML = '<div id="ppmErrorBox" style="padding: 4px;"><em>' + msg + '</em></div>';
	} else {
		loginErrorDiv = document.getElementById("loginErrorContainer");
		loginErrorDiv.innerHTML = '<div id="errorBox" style="padding: 4px;"><em>' + msg + '</em></div>';
	}
}