/*  GameHouse.com Script, version 0.1.0.
 *  (c) 2008 GameHouse.com
 *
 *--------------------------------------------------------------------------*/

// START - Unobtrusive Events //
// ************************** //
document.observe("dom:loaded", function() {
	buildPreferenceElements();
	drawersLeftnav();
	customizeLeftnav();
	rewriteSupportNote();
	userProfileSetup();
	customerSupportSetup();
});

Event.observe(window, 'load', function() {
	//observeClickArray($$('.customer_support_form_toggle'),helpBlockToggle,1);
	//observeClickStringId('customer_support_close_button',helpBlockToggle);
	//observeClickStringId('cancel_help',helpBlockToggle);

	observeClickStringId('update_email_js',updateEmailBlockToggle);
	observeClickStringId('profile_email_close_button',updateEmailBlockToggle);
	observeClickStringId('cancel_email',updateEmailBlockToggle);

	observeClickStringId('update_password_js',updatePasswordBlockToggle);
	observeClickStringId('profile_password_close_button',updatePasswordBlockToggle);
	observeClickStringId('cancel_password',updatePasswordBlockToggle);

	observeClickStringId('customizeLeftnav_button',chpBlockToggle);
	observeClickStringId('chp_close_button',chpBlockToggle);
	observeClickStringId('button_chp_ok',chpBlockToggle);
	observeClickStringId('login_block_toggle',loginBlockToggle);
	observeClickStringId('button_cancel',loginBlockToggle);
	observeClickArray($$('#pop_chp_box input'),customizeLeftnav);
	observeClickArray($$('#content_bb h3.drawer'),drawersLeftnav);
	observeClickArray($$('.clickPopUp'),popUpOnlineGame,1);
	observeClickArray($$('.carousel_next_button img'),carouselNextButton);
	observeClickArray($$('.carousel_previous_button img'),carouselPrevButton);
	observeClickArray($$('#customer_service_infobox ul li span'),answerDrawerToggle,1);
});
// ************************ //
// END - Unobtrusive Events //

// START initializers //
// ****************** //
function carouselNextButton() { moveCarousel('next', 'carousel_id_01'); return false; }
function carouselPrevButton() { moveCarousel('prev', 'carousel_id_01'); return false; }
//function helpBlockToggle(e) { var id = 'customer_support_help'; blockToggle(id); }
function updateEmailBlockToggle() { var id = 'user_profile_email'; blockToggle(id); }
function updatePasswordBlockToggle() { var id = 'user_profile_password'; blockToggle(id); }
function chpBlockToggle() { var id = 'pop_chp_box'; blockToggle(id); }
function loginBlockToggle() { var id = 'pop_login_box'; blockToggle(id); }
// **************** //
// END initializers //


// START Event Observe Functions //
// ***************************** //


function observeClickStringId(elementIdString, funct) {
/*{ "Summary": "Attached an element to a function for unobtrusive events.",
	"Arguments": {
		"elementIdString": "Accepts a string for an element ID.",
		"funct": "Accepts a function.",
	}
}  */
	if (Object.isString(elementIdString))
	{
		if (Object.isElement($(elementIdString))) { Event.observe($(elementIdString),'click',funct); }
		else { return false; }
	}
	else { return false; }
}


function observeClickArray(elementArray, funct) {
/*{ "Summary": "Attached an element to a function for unobtrusive events.",
	"Arguments": {
		"elementArray": "Accepts an array of elements.",
		"funct": "Accepts a function.",
		"bind": "If set to 1 creates a event binding to the element that triggered the event."
	}
}  */
	if (Object.isArray(elementArray) && Object.isElement(elementArray[0]))
	{
		for(var i=0;i < elementArray.length;i++) { 
			Event.observe(elementArray[i],'click',funct.bindAsEventListener(this));
		}
	}
	else { return false; }
}


function observeClickElement(element, funct) {
/*{ "Summary": "Attached an element to a function for unobtrusive events.",
	"Arguments": {
		"element": "Accepts an element.",
		"funct": "Accepts a function.",
	}
}  */
	if (Object.isElement(element)) { Event.observe(element,'click',funct); }
	else { return false; }
}


// **************************** //
// END  Event Observe Functions //


// START - Functions //
// ***************** //
function blockToggle(id) {
/*{ "Summary": "Toggle a block element between display block and display none.",
	"Arguments": {
		"id": "Accepts an element."
	}
}  */
	var element = $(id);
	if (element.style.display !== 'block') { element.style.display='block'; }
	else { element.style.display='none'; }
	return false;
}


// START - Cookie Functions //
function createCookie(name,value,days) {
/*{ "Summary": "Create a cookie.",
	"Arguments": {
		"name": "Name of the cookie.",
		"value": "Value of the Cookie.",
		"days": "Duration of the cookie in days."
	}
}  */
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


function readCookie(name) {
/*{ "Summary": "Read a cookie.",
	"Arguments": {
		"name": "Name of the cookie to read."
	}
}  */
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function eraseCookie(name) {
/*{ "Summary": "Delete a Cookie.",
	"Arguments": {
		"name": "Name of the cookie to delete."
	}
}  */
	createCookie(name,"",-1);
}


function jsonToCookie(cookieName,groupName,jsonString,cookieDays) {
/*{ "Summary": "Add JSON string to a cookie.",
	"Arguments": {
		"cookieName": "Name of the cookie the JSON string should be saved into.",
		"groupName": "Name of the group or set this JSON string should be saved under (there can be more than one set/group per cookie).",
		"jsonString": "A JSON string to be saved.",
		"cookieDays": "Duration of the cookie in days."
	}
}  */
	var currentCookie = readCookie(this.cookieName);
	var jsonGroup = (currentCookie) ? currentCookie : '{\"' + groupName + '\": ' + jsonString + '}';
	var cookieHash = $H(jsonGroup.evalJSON(true));
	cookieHash.set(groupName,$H(jsonString.evalJSON(true)));
	var jsonCookie = cookieHash.toJSON();
	this.createCookie(cookieName,jsonCookie,cookieDays);
}


function serialToJSON(serial) {
/*{ "Summary": "convert a serialized string to JSON.",
	"Arguments": {
		"serial": "a serialized string."
	}
}  */
	var stringJSON = (serial) ? $H(serial.toQueryParams()).toJSON() : false;
	return stringJSON;
}


function serializeElements(element) {
/*{ "Summary": "serializes elements enclosing form of a form.",
	"Arguments": {
		"element": "an element that is contained in a form."
	}
}  */
	if (Object.isElement($(element))) {
		var serial = $(element).up('form').serialize();
		return serial;
	}
	else { alert('not element'); return false; }
}

// END - Cookie Functions //

function drawer(e) {
/*{ "Summary": "Left nav drawer constructor.",
	"Arguments": {
		"e": "An event."
	}
}  */
	this.e = e;
	this.cookieName = 'prefcookie';
	this.currentCookie = readCookie(this.cookieName);
	this.preferenceGroupName = 'drawer';
	this.preferenceGroupDef = '{"pref_0": "on"}';
	this.preferenceGroupCurrent = this.preferenceGroupDef;
	this.cookieDays = 365;
	this.triggers = $$('#content_bb div div.pref h3');
	this.containers = $$('#content_bb div div.pref');
	this.isClick = false;
	if (this.e !== undefined) {
		// find the object that the event was fired in.
		this.t = Event.element(this.e);
		this.isClick = true;
	}
	
	this.jsonToCookie = jsonToCookie;
	this.createCookie = createCookie;
	this.drawerCore = drawerCore;
	this.preferenceOnLoadSetup = preferenceOnLoadSetup;
	this.drawerOnClickSave = drawerOnClickSave;
	this.drawerSetView = drawerSetView;
}

function drawersLeftnav(e) {
/*{ "Summary": "New left nav drawer object.",
	"Arguments": {
		"e": "An event."
	}
}  */
	var leftNavDrawer = new drawer(e);
	leftNavDrawer.drawerCore();
}

function drawerCore() {
	var preference = this.preferenceOnLoadSetup(this.preferenceGroupDef);
		preference = this.drawerOnClickSave(preference);
	this.drawerSetView(preference);
}

function drawerOnClickSave(preference) {
	if (this.isClick) {
		this.t.up().toggleClassName('on');
		var preferenceGroupSerial = '';
		for(var i=0;i < this.containers.length;i++) {
			if(this.containers[i].hasClassName('on')) {
				preferenceGroupSerial = preferenceGroupSerial + '&pref_' + i + '=on';
			}
		}
		var preferenceGroupJSON = (preferenceGroupSerial === "") ? '{}' : serialToJSON(preferenceGroupSerial);
		this.jsonToCookie(this.cookieName,this.preferenceGroupName,preferenceGroupJSON,this.cookieDays);
		return preferenceGroupJSON;
	}
	return preference;
}


function drawerSetView(preference) {
	for(var i=0;i < this.triggers.length;i++) {
		this.headerID = this.triggers[i].up().identify();
		this.drawerID = this.triggers[i].next();
		if (!preference.include(this.headerID)) {
			var drawerState = false;
			this.triggers[i].up().removeClassName('on');
		}
		else {
			var drawerState = true;
			this.triggers[i].up().addClassName('on');
		}
		if (this.t == this.triggers[i]){
			if(this.containers[i].hasClassName('on')) {
				new Effect.Opacity(this.drawerID, { from: 0.0, to: 1.0, duration: 0.2 });
				Effect.SlideDown(this.drawerID, { duration: 0.2 });
			}
			else {
				new Effect.Opacity(this.drawerID, { from: 1.0, to: 0.0, duration: 0.2 });
				Effect.SlideUp(this.drawerID, { duration: 0.2 });
			}
		}
		else {
			var drawerStyle = (drawerState === true)? "block" : "none" ;
			this.drawerID.style.display=drawerStyle;
		}
	}
}


function customize(e) {
// Set variables.
	this.e = e;
	this.cookieName = 'prefcookie';
	this.currentCookie = readCookie(this.cookieName);
	this.preferenceGroupName = 'customize';
	this.preferenceGroupDef = '{"pref_0": "on", "pref_1": "on", "pref_5": "on", "pref_6": "on"}';
	this.preferenceGroupCurrent = this.preferenceGroupDef;
	this.formName = 'form_chp_box';
	this.formChild = 'label';
	this.formChildren = $$('#' + this.formName + ' ' + this.formChild);
	this.formInput = 'input';
	this.cookieDays = 365;
	this.preID = 'check_';
	this.isClick = false;
	if (this.e !== undefined) {
		// find the object that the event was fired in.
		this.t = Event.element(this.e);
		this.isClick = true;
	}
	
	this.jsonToCookie = jsonToCookie;
	this.createCookie = createCookie;
	this.customizeCore = customizeCore;
	this.preferenceOnLoadSetup = preferenceOnLoadSetup;
	this.customizeOnClickSave = customizeOnClickSave;
	this.customizeSetView = customizeSetView;
}


function customizeLeftnav(t) {
	var leftNavCustomize = new customize(t);
	leftNavCustomize.customizeCore();
}

function customizeCore() {
	var preference = this.preferenceOnLoadSetup(this.preferenceGroupDef);
		preference = this.customizeOnClickSave(preference);
	this.customizeSetView(preference);
}

function customizeOnClickSave(preference) {
	if (this.isClick) {
		var preferenceGroupJSON = serialToJSON(serializeElements(this.t));
		this.jsonToCookie(this.cookieName,this.preferenceGroupName,preferenceGroupJSON,this.cookieDays);
		return preferenceGroupJSON;
	}
	return preference;
}


function customizeSetView(preference) {
	for(var i=0;i < this.formChildren.length;i++) {
		this.checkboxid = this.formChildren[i].down().identify();
		this.baseid = this.checkboxid.gsub(this.preID, '');
		var thisid = (this.t) ? $(this.t).identify() : false ;
		if (!preference.include(this.baseid)) {
			var customizeState = false;
		}
		else {
			var customizeState = true;
		}
		if (thisid == this.checkboxid){
			if($(this.checkboxid).checked) {
				Effect.SlideDown(this.baseid, { duration: 0.3 });
				new Effect.Opacity(this.baseid, { from: 0.0, to: 1.0, duration: 0.3 });
				new Effect.Highlight(this.baseid);
			}
			else {
				Effect.SlideUp(this.baseid, { duration: 0.3 });
				new Effect.Opacity(this.baseid, { from: 1.0, to: 0.0, duration: 0.3 });
			}
		}
		else {
			var checkboxStyle = (customizeState === true)? true : false ;
			var customizeStyle = (customizeState === true)? "block" : "none" ;
			$(this.checkboxid).checked=checkboxStyle;
			$(this.baseid).style.display=customizeStyle;

		}
	}
}


function preferenceOnLoadSetup(preference) {
	if (!this.isClick) {
		if (this.currentCookie === null) {
			this.jsonToCookie(this.cookieName,this.preferenceGroupName,preference,this.cookieDays);
		}
		else {
			this.cookieHash = $H(this.currentCookie.evalJSON(true));
			if (this.cookieHash.get(this.preferenceGroupName) === undefined) {
				this.jsonToCookie(this.cookieName,this.preferenceGroupName,preference,this.cookieDays);
			}
			else { return Object.toJSON($H(this.currentCookie.evalJSON(true)).get(this.preferenceGroupName)); }
		}
	}
	return preference;
}


function buildPreferenceElements() {
/*{ "Summary": "Adds seqential IDs for left nav DIVs and builds checkbox list from leftnav DIVs for customize feature.",
}  */
	this.containers = $$('#content_bb div div.pref');
	this.triggers = $$('#form_chp_box fieldset');
	this.checkbox = new Array()
	this.checkboxes = '';
	if (Object.isElement(this.containers[0]) && Object.isElement(this.triggers[0])) {
		for(var i=0;i < this.containers.length;i++) {
			Element.writeAttribute(this.containers[i], 'id', value = 'pref_' + i)
			var title = this.containers[i].down().innerHTML;
			this.checkbox[i] = '<label for="check_pref_' + i + '">\n\t<input name="pref_' + i + '" id="check_pref_' + i + '" type="checkbox" />' + title +'\n</label>\n';
			this.checkboxes = this.checkboxes + this.checkbox[i];
		}
		this.checkboxes = this.checkboxes + '<img id="button_chp_ok" src="/beta/css/images/button_ok.gif" alt="button_ok.gif" width="115" height="30" />';
		this.triggers[0].update(this.checkboxes);
	}
}

function moveCarousel(direction, id) {
/*{ "Summary": "Scrolls carousel panels.",
	"Arguments": {
		"direction": "Direction of scroll, accepts "prev" and "next".",
		"id": "The ID of the element to scroll."
	}
}  */
	var carousel = $(id);
	var slides = carousel.childElements();
	var total = slides.length;
	var width = $(slides[0]).getWidth();
	// If element is not offset set x to 0 otherwise set x to offset amount.
	var x = ($(id).getStyle('left') == null) ? '0px' : $(id).getStyle('left');
	x = String(x.substring(0, (x.length - 2)));
	// detect next button click and set slide number.
	if (direction == 'next') { 
		var slide = (x == 0) ? 2 : ((Math.abs(x) / width) + 2);
	}
	// detect previous button click and set slide number.
	else if (direction == 'prev') { 
		var slide = (Math.abs(x) / width);
	}
	else {
		return false;
	}
	// If at beginning or end of slide sequence return false.
	if (!$(slides[slide - 1])) {
		return false;
	}
	if (direction == 'next') {
		if (x > -(width * (total - 1))) {
			new Effect.MoveBy(id, 0, 0 , { x: -width, y: 0, duration: 0.7,  transition: Effect.Transitions.sinoidal});
			return true;
		}
	} 
	else if (direction == 'prev') {
		if (x < 0) {
			new Effect.MoveBy(id, 0, 0 , { x: width, y: 0, duration: 0.7,  transition: Effect.Transitions.sinoidal});
			return true;
		}
	} 
	else {
		return false;
	}
	return false;
}


function popUpOnlineGame(e) {
/*{ "Summary": "Create pop-up for online games.",
	"Arguments": {
		"e": "An event."
	}
}  */
	var e = e;
	var t = Event.element(e);
	var popupURL = t.readAttribute("value");
	var width = 1000;
	var height = 850;
	var leftPosition = (screen.width) ? (screen.width-width)/2 : 0;
	var topPosition = (screen.height && (screen.height >= 600)) ? (screen.height-height)/2 : 0;
	var settings = 'width='+width+',height='+height+',left='+leftPosition+',top='+topPosition+'toolbar=0,location=0,directories=0,menubar=0,scrollbar=0,resizable=0,status=0';
	var popup = window.open(popupURL, 'gamepopup', settings);
	if (popup != null) popup.focus();
}

function rewriteSupportNote() {
	if($('support_note')){
		var supportNote = $('support_note').innerHTML;
		supportNote = supportNote.gsub('==Support Note==','')
		supportNote = supportNote.gsub('==End Support Note==','<br />')
		$('support_note').update(supportNote)
	}
	else { return false; }
}

function answerDrawerToggle(e) {
	var e = e;
	var t = Event.element(e);
	var drawer = t.next();
	if(!drawer.hasClassName('on')) {
		drawer.addClassName('on');
	}
	else {
		drawer.removeClassName('on');
	}
}

function mask() {
	$('page').up('body').insert('<div id="mask">&nbsp;</div>','bottom');
	var mask = $('mask');
	if(!mask.hasClassName('on')) {
		mask.addClassName('on');
	}
	else {
		mask.removeClassName('on');
	}
}

function userProfileSetup() {
	if($('user_profile_buttons')){
		$('user_profile_buttons').style.display="block";
	}
	if($('user_profile_email')){
		emailBox = $('user_profile_email');
		emailBox.style.display="none";
		emailBox.addClassName('on');

	}
	if($('user_profile_password')){
		passwordBox = $('user_profile_password');
		passwordBox.style.display="none";
		passwordBox.addClassName('on');
	}
	else { return false; }
}

function customerSupportSetup() {
	if($('customer_support_help')){
		emailBox = $('customer_support_help');
		emailBox.style.display="none";
		emailBox.addClassName('on');
	}
	else { return false; }
}













