/// <reference path="../../Prototype/prototype.js" />
/// <reference path="../Error/ErrorHandler.js" />
/// <reference path="../sureflix.js" />

/**
* @uses lib/Prototype/Prototype.js
* @uses lib/Sureflix/Sureflix.js
* @uses lib/Sureflix/Error/ErrorHandler.js
*/

/**
* @namespace This namespace contains classes for individual widgets. Classes are implemented inside /pc/Templates/Widgets/
* @author erik 02/17/2009
*/

Sureflix.Widgets = {};

//Shorthand
SxWi = Sureflix.Widgets;


/*******************************************/
/*** HunkRegisterBox Widget Begin        ***/
/*******************************************/

Sureflix.Widgets.HunkRegisterBox = {};

Sureflix.Widgets.HunkRegisterBox.Focus = function(event, idModifier) {
	var textInput = $("SureHunkRegisterBoxInput" + idModifier);
	if (textInput.hasClassName("SureHunkRegisterBoxPrompt")) {
		textInput.value = "";
		textInput.removeClassName("SureHunkRegisterBoxPrompt");
	}
	return true;
};

Sureflix.Widgets.HunkRegisterBox.KeyDown = function(event, idModifier) {
	var key = (isNav ? event.which : window.event.keyCode);
	if (key == 13) {
		Sureflix.Widgets.HunkRegisterBox.Submit(idModifier);
		return false;
	} else {
		return true;
	}
};

Sureflix.Widgets.HunkRegisterBox.Submit = function(idModifier) {
	var email = $F("SureHunkRegisterBoxInput" + idModifier);
	if ((email == "") || (email.indexOf(" ") != -1) || (email.indexOf("@") == -1) || (email.indexOf(".") == -1)) {
		alert(jsErrEmailEnter);
		return false;
	}
	if (!window.open("register.asp?Email=" + URLencode(email), "popup", "width=450,height=200,scrollbars=no,toolbar=no,directories=no,resizable=no,status=no")) {
		PopupBlocked(); //**** TODO: Move to Sureflix.Utilities namespace
	}
	return false;
};

/*******************************************/
/*** HunkRegisterBox Widget End          ***/
/*******************************************/


/*******************************************/
/*** StarMasthead Widget Begin           ***/
/*******************************************/

Sureflix.Widgets.StarMasthead = {};

Sureflix.Widgets.StarMasthead.MouseOver = function(event, idModifier) {
	$("SureStarMastheadCaption" + idModifier).show();
}

Sureflix.Widgets.StarMasthead.MouseOut = function(event, idModifier) {
	$("SureStarMastheadCaption" + idModifier).hide();
}

/*******************************************/
/*** StarMasthead Widget End             ***/
/*******************************************/

/*******************************************/
/*** QuickSearch Widget Begin            ***/
/*******************************************/

Sureflix.Widgets.QuickSearch = Class.create({
	initialize: function(idModifier, submitAction, itemSelectedAction, dontSubmit) {
		this.dontSubmit = dontSubmit || false;
		this.idModifier = idModifier || "";
		this.submitAction = submitAction || "SmartSearch.asp?Fields=Phrase&Values={actionParams0}";
		this.itemSelectedAction = itemSelectedAction || "QuickSearch.asp?Text={actionParams0}&QuickSearch={actionParams1}";
		this.textInputID = "SureQuickSearchInput";
		this.submitElementID = "SureQuickSearchSubmit";
		this.loadingElementID = "SureQuickSearchLoading";
		this.promptClassName = "SureQuickSearchPrompt";
		this.itemSelectedSubmitted = false; //private
		this.callback;
		// try to attach
		this.AttachEvents();
	},


	GetTextInputID: function() {
		return this.getElementIdWithModifier(this.textInputID);
	},
	GetLoadingElementID: function() {
		return this.getElementIdWithModifier(this.loadingElementID);
	},
	GetSubmitElementID: function() {
		return this.getElementIdWithModifier(this.submitElementID);
	},
	getElementIdWithModifier: function(id) {	//private
		return id + this.idModifier;
	},

	// This will do nothing if the elements aren't all already created in the DOM
	AttachEvents: function() {
		var textInput = $(this.GetTextInputID());
		var submitElement = $(this.GetSubmitElementID());
		var loadingElement = $(this.GetLoadingElementID());

		if (!textInput || !submitElement || !loadingElement) return;

		textInput.observe('focus', this.Focus.bindAsEventListener(this));
		textInput.observe('blur', this.Blur.bindAsEventListener(this));
		textInput.observe('keypress', this.KeyDown.bindAsEventListener(this));
		submitElement.observe('click', this.submit.bind(this));
		loadingElement.observe('click', this.submit.bind(this));
	},

	Focus: function(event) {
		var textInput = $(this.GetTextInputID());
		if (textInput.hasClassName(this.promptClassName)) {
			textInput.value = "";
			textInput.removeClassName(this.promptClassName);
		} else {
			textInput.select();
		}
		this.isFocused = true;
		return true;
	},

	Blur: function(event) {
		this.isFocused = false;
		return true;
	},

	KeyDown: function(event) {
		if (event.keyCode == Event.KEY_RETURN) {
			this.submit();
			return (false);
		} else {
			return (true);
		}
	},

	/**
	* Submits the QuickSearch form to SmartSearch.asp. 
	* (ItemSelected submits to QuickSearch.asp)
	* @return {void}
	*/
	submit: function() {
		//don't submit if ItemSelected has already submitted
		if (this.hasItemSelectedBeenSubmitted() || this.dontSubmit) return;
		
		//if (!this.isFocused) return;
		var text;
		var textInput = $(this.GetTextInputID());
		if (textInput.hasClassName(this.promptClassName)) {
			text = "";
		} else {
			text = $F(this.GetTextInputID());
		}
		var action = this.getReplacedAction(this.submitAction, { 0: encodeURIComponent(text) })

		this.submitForm(action);
	},

	submitForm: function(action, quickSearchID) {
		if (this.dontSubmit) {
			var text = $F(this.GetTextInputID());
			this.callback(text, quickSearchID);
			return;
		}
		document.thisForm.action = action;
		document.thisForm.submit();
		this.ShowLoading(true);
	},

	/**
	* Submits the QuickSearch form when an item is selected from the dropdown menu
	* @return {void}
	*/
	ItemSelected: function(textBox, li) {
		var quickSearchID = li.id;
		var text = $F(textBox);
		var action = this.getReplacedAction(this.itemSelectedAction, { 0: encodeURIComponent(text), 1: quickSearchID });

		this.itemSelectedSubmitted = true;
		this.submitForm(action, quickSearchID);
	},

	hasItemSelectedBeenSubmitted: function() { //private
		return this.itemSelectedSubmitted;
	},

	ShowLoading: function(permanently) {
		var loadingElement = $(this.GetLoadingElementID());
		if (!loadingElement) return;

		loadingElement.makeVisible();
		if (permanently) {
			$(this.GetSubmitElementID()).setStyle("background-image", $(this.GetLoadingElementID()).getStyle("background-image"));
		}
	},

	HideLoading: function() {
		var loadingElement = $(this.GetLoadingElementID());
		if (!loadingElement) return;

		loadingElement.makeHidden();
	},

	getReplacedAction: function(action, paramsObject) {	//private
		var replacedAction = action;
		if (paramsObject != null) {
			replacedAction = replacedAction.replace("{actionParams0}", paramsObject[0]);
			replacedAction = replacedAction.replace("{actionParams1}", paramsObject[1]);
		}
		return replacedAction;
	}
});


/*******************************************/
/*** QuickSearch Widget End              ***/
/*******************************************/




/*******************************************/
/*** AutoComplete Widget Begin            ***/
/*******************************************/

Sureflix.Widgets.AutoCompleteList = Class.create({
	initialize: function(idModifier, inputElementID, hiddenFieldID, initialValuesArray) {
		this.idModifier = idModifier || "";
		this.inputElementID = inputElementID;
		this.hiddenFieldID = hiddenFieldID;
		this.listItemsElementId = "SureAutoCompleteList" + this.idModifier;
		this.itemSpanId = "SureAutoCompleteItem";
		this.listItems = new Array();
		this.initialValuesArray = initialValuesArray || null;
		if (this.initialValuesArray) {
			this.listItems = initialValuesArray;
		} 
		this.buildItemList();
	},

	AddItem: function(selectedItem) {
		this.listItems.push(selectedItem);
		$(this.inputElementID).value = "";
		this.buildItemList();

	},
	buildItemList: function() {
		var starsHTML = "";
		this.listItems = this.removeDuplicate(this.listItems);

		for (var i = 0; i < this.listItems.length; i++) {

			starsHTML += "<span id='down" + this.itemSpanId + this.idModifier + i + "' style='float:right;'><a style='cursor:pointer;color:blue;'><strong>&nbsp;&#8681;&nbsp;</strong></a></span><span id='up" + this.itemSpanId + this.idModifier + i + "' style='float:right;'><a style='cursor:pointer;color:green'><strong>&nbsp;&#8679;&nbsp;</strong></a>&nbsp;</span><span id=\"" + this.itemSpanId + this.idModifier + i + "\" class=\"" + this.itemSpanId + this.idModifier + "\">" + this.listItems[i] + "&nbsp;<a style='cursor:pointer;color:red'><b><big>&#215;</big></b></a></span><br/>";

		}

		$(this.listItemsElementId).innerHTML = starsHTML;

		var elements = $$("span." + this.itemSpanId + this.idModifier);
		for (var i = 0; i < elements.length; i++) {
			Event.observe(elements[i], 'click', this.removeArrayElement.bindAsEventListener(this));

			$('down' + this.itemSpanId + this.idModifier + i).observe('click', this.moveDown.bindAsEventListener(this));
			$('up' + this.itemSpanId + this.idModifier + i).observe('click', this.moveUp.bindAsEventListener(this));

		}

		$(this.hiddenFieldID).value = this.parseIDs();
	},

	removeDuplicate: function (arrayInput) {
		var arrayOutput = new Array();
		for (var i = 0; i < arrayInput.length; i++) {
			var valid = true;
			for (var j = i + 1; j < arrayInput.length; j++) {
				if (arrayInput[i] == arrayInput[j])
					valid = false;
			}
			if (valid == true)
				arrayOutput.push(arrayInput[i]);
		}
		return arrayOutput;
	},

	moveUp: function (event) {
		var span = Event.findElement(event, 'span');
		this.rearrangeArray("up", span.id.replace("up" + this.itemSpanId + this.idModifier, ''));

	},

	moveDown: function (event) {
		var span = Event.findElement(event, 'span');
		this.rearrangeArray("down", span.id.replace("down" + this.itemSpanId + this.idModifier, ''));

	},

	rearrangeArray: function (direction, indexToMove) {

		indexToMove = parseInt(indexToMove);
		if (direction == "up" && indexToMove != 0) {
			this.listItems.splice((indexToMove - 1), 0, (this.listItems.splice(indexToMove, 1) + ""));

		} else if (direction == "down" && indexToMove != this.listItems.length) {
			this.listItems.splice((indexToMove + 1), 0, (this.listItems.splice(indexToMove, 1) + ""))
		}

		this.buildItemList();
	},

	parseIDs: function () {
		var newArray = new Array();
		for (var i = 0; i < this.listItems.length; i++) {
			var key = (this.listItems[i] + "").split(":")[0];
			if (newArray.indexOf(key) < 0) {
				newArray.push(key);
			}
		}
		return newArray;
	},
	removeArrayElement: function(event) {
		var span = Event.findElement(event, 'span')
		var indexToRemove = span.id.replace(this.itemSpanId + this.idModifier, '');
		this.listItems.splice(indexToRemove, 1);
		this.buildItemList();
	}
});

/*******************************************/
/*** AutoComplete Widget End             ***/
/*******************************************/


/*******************************************/
/*** FlexList Widget Begin               ***/
/*******************************************/

Sureflix.Widgets.FlexList = {
	lists: $H(),
	initialHash: "",
	locationHash: "",
	watchBackButtonInterval: null
};

SxFl = Sureflix.Widgets.FlexList;

SxFl.initialize = function(listID) {
	if (this.initialHash != "") return;
	var list = this.findList(listID);
	list.initialize();
	this.updateRentals();
}

SxFl.createList = function(listID) {
	var list = new SxFl.List(listID);
	this.lists.set(listID, list);
	return list;
}

SxFl.findList = function(listID) {
	var list = this.lists.get(listID);
	return list;
}

SxFl.updateRentals = function() {
	for (var i = 0, len = this.rentals.length; i < len; ++i) {
		var rental = this.rentals[i];
		var itemID = ".SureSceneItem_" + rental.movie + "_" + rental.scene;
		$$(itemID + " .SureScenePrice").each(function(elem) { elem.hide(); });
		$$(itemID + " .SureSceneRented").each(function(elem) { elem.show(); });
	}
}

SxFl.saveInitialHash = function(list) {
	if (this.initialHash == "") {
		this.initialHash = list.getHashString();
	}
}

SxFl.watchBackButton = function(locationHash) {
	this.locationHash = document.location.hash;

	this.watchBackButtonInterval = setInterval(function() {
		if (document.location.hash != SxFl.locationHash) {
			try {
				var listID = SxUt.getHashParam("listID");
				var list = SxFl.findList(listID);
				list.setToLocationHash(document.location.hash);
			} catch (e) {
				console.error('FlexList: unknown hash change');
			}
		}
	}, 100);
}

SxFl.stopWatchingBackButton = function() {
	if (this.watchBackButtonInterval == null) return;

	clearInterval(this.watchBackButtonInterval);
	this.watchBackButtonInterval = null;
}

SxFl.List = function(listID) {
	this.id = listID;
	this.itemType = "";
	this.layout = "";
	this.page = 0;
	this.itemsPerPage = 0;
	this.defaultSort = "";
	this.sort = "";
	this.join = "";
	this.where = "";
	this.tagZone = "";
	this.design = "";
	this.movieZone = "";
	this.daysABCD = "";
	this.rentalDays = 0;
	this.lang = "";
	this.curcy = "";
	this.hard = false;
	this.optionsBar = true;
	this.navBar = true;
}

SxFl.List.prototype.initialize = function() {
	if (!this.navBar) return;

	var documentHash = document.location.hash.toString();
	var listHash = this.getHashString();
	if (documentHash != listHash && SxUt.getHashParam("listID") == this.id) {
		this.setToLocationHash(documentHash);
	} else {
		document.location.replace(SxUt.replaceHash(listHash));
	}
	SxFl.saveInitialHash(this);
}

SxFl.List.prototype.loadList = function(parameters) {
	var webServiceUrl = "http://" + document.location.host + "/pc/Services/FlexListService.asp";

	new Ajax.Request(
		webServiceUrl, {
			method: 'POST',
			asynchronous: true,
			parameters: parameters,
			onSuccess: function(transport) {
				var listID = transport.request.parameters.id;
				SxFl.findList(listID).loadListCompleted(transport);
			}
		}
	);
}

SxFl.List.prototype.getRootElement = function(transport) {
	return $("Sure" + this.id + "FlexList");
}

SxFl.List.prototype.loadListCompleted = function(transport) {
	var result = transport.responseText;
	var parameters = transport.request.parameters;

	this.getRootElement().replace(result);
	this.scrollToTop();

	this.page = parameters.page;
	this.itemType = parameters.itemType;
	this.layout = parameters.layout;
	this.sort = parameters.sort;
	this.itemsPerPage = parameters.itemsPerPage;

	this.updateHash();
	SxFl.updateRentals();
	SxUi.HoverScenePic.setup();
}

SxFl.List.prototype.scrollToTop = function(transport) {
	var rootElement = this.getRootElement();
	if (rootElement.viewportOffset().top < 0) {
		rootElement.scrollTo();
	}
}

SxFl.List.prototype.updateHash = function() {
	SxFl.stopWatchingBackButton();

	var hash = this.getHashString();
	if (document.location.hash == "" && hash == SxFl.initialHash) {
		return;
	}
	if (document.location.hash != hash) {
		document.location.hash = hash;
	}

	SxFl.watchBackButton();
}

SxFl.List.prototype.getHashString = function() {
	return "#listID=" + this.id + "&page=" + this.page + "&itemsPerPage=" + this.itemsPerPage + "&itemType=" + this.itemType + "&layout=" + this.layout + "&sort=" + this.sort;
}

SxFl.List.prototype.setToLocationHash = function(hashString) {
	var parameters = Object.clone(this);
	try {
		parameters.page = parseInt(SxUt.getHashParam("page", this.page, hashString));
		parameters.itemType = SxUt.getHashParam("itemType", this.itemType, hashString);
		parameters.layout = SxUt.getHashParam("layout", this.layout, hashString);
		parameters.sort = SxUt.getHashParam("sort", this.sort, hashString);
		parameters.itemsPerPage = parseInt(SxUt.getHashParam("itemsPerPage", this.itemsPerPage, hashString));
	} catch (e) {
		console.error('FlexList.List: unknown hash change');
	}
	this.loadList(parameters);
}

SxFl.List.prototype.setPage = function(page) {
	var parameters = Object.clone(this);
	parameters.page = page;
	this.loadList(parameters);
}

SxFl.List.prototype.setItemType = function(itemType) {
	SxUt.SetCookie("ListItemType", itemType);
	var parameters = Object.clone(this);
	parameters.itemType = itemType;
	parameters.page = 1;
	this.loadList(parameters);
}

SxFl.List.prototype.setLayout = function(layout) {
	SxUt.SetCookie("ListLayout", layout);
	var parameters = Object.clone(this);
	parameters.layout = layout;
	parameters.page = 1;
	this.loadList(parameters);
}

SxFl.List.prototype.setSelectedSort = function() {
	var sortSelect = $$("#Sure" + this.id + "FlexList .SureListOptionsSort select")[0];
	var sort = SxUi.SelectUtils.getValue(sortSelect);
	this.setSort(sort);
}

SxFl.List.prototype.setSort = function(sort) {
	SxUt.SetCookie("Sort", sort);
	var parameters = Object.clone(this);
	parameters.sort = sort;
	parameters.page = 1;
	this.loadList(parameters);
}

SxFl.List.prototype.setSelectedItemsPerPage = function() {
	var itemsSelect = $$("#Sure" + this.id + "FlexList .SureListOptionsItemsPerPage select")[0];
	var itemsPerPage = parseInt(SxUi.SelectUtils.getValue(itemsSelect));
	this.setItemsPerPage(itemsPerPage);
}

SxFl.List.prototype.setItemsPerPage = function(itemsPerPage) {
	SxUt.SetCookie("ListItemsPerPage", itemsPerPage);
	var parameters = Object.clone(this);
	parameters.itemsPerPage = itemsPerPage;
	parameters.page = 1;
	this.loadList(parameters);
}

SxFl.List.prototype.setSelectedRentalDays = function() {
	var rentalDaysSelect = $$("#Sure" + this.id + "FlexList .SureListOptionsRentalDays select")[0];
	var rentalDays = parseInt(SxUi.SelectUtils.getValue(rentalDaysSelect));
	this.setRentalDays(rentalDays);
}

SxFl.List.prototype.setRentalDays = function(rentalDays) {
	SxUt.SetCookie("RentalDays", rentalDays);

	var parameters = Object.clone(this);
	parameters.rentalDays = rentalDays;
	this.loadList(parameters);
}

/*******************************************/
/*** FlexList Widget End                 ***/
/*******************************************/
