/**
 * Contains the basic functionality needed for Atari.com
 * It should be used for helper methods and for instantiation of global objects
 * across the site, such as Flash embedding, main navigation, etc.
 * 
 * @author Kevin Sweeney (Fi)
 * @author David Lindkvist (Fi)
 * @author Karl Stanton (Fi)
 * @author Filip Michalowski (Fi)
 * @version 1.0
 * 
 */

var AtariGlobal = {};

// Properties __________________________________________________________________

AtariGlobal.min_flash_version = '9.0.115';






// General Methods _____________________________________________________________

/**
 * Iniatilizes any global behaviors required throughout the site
 */
AtariGlobal.init = function () {
	
	//$.log.info('Loading global Atari Javascript - init()');
	
	// Unbind event listeners
	$(document).unload(function () {
		$('*').unbind();
	});

	AtariGlobal.setupPreloadSprites();
	
	AtariGlobal.setupSpotlightSearch();
	
	AtariGlobal.setupExternalLinks();
	
	if($('body').attr('id') !== 'arcade'){
		AtariGlobal.setupTopMenu();	
	}
		
	AtariGlobal.setupSelects();
	
	AtariGlobal.setupSearchInput();
	
	AtariGlobal.setupInputFields();
	
	AtariGlobal.setupFormButtonsIE8();

	// Hook up click event for newsletter popup
	/* $('a.newsletterPopup', '#footer li.news').click(function () {
		 AtariGlobal.RegisterPopUp();
		 return false;
	}); */
	

};

/**
 * Initializes the spotlight search functionality for 
 */
AtariGlobal.setupSpotlightSearch = function () {
	
	// Disable the submission of the form
	$('#searchSpotLightForm').submit(function () {
		return false;
	});
	
	$("#gamesSpotlightInput").spotlight({
			minlength: 1,
			searchpath: "/ajax/spotlight.php",
			localizedHelperText: localized_strings.menu_label_FindGames
	});
	
	// show games spotlight in menu
	$('#gamesSpotlight').show();
	
};

/**
 * Initialize external links
 */
AtariGlobal.setupExternalLinks = function () {	
	$("a[rel='external']").attr("target","_blank");
};

/**
 * Sets up the rollover / hover states for the top menu
 * This will (obviously) only work for people with JS, else it will fall back on CSS
 */
AtariGlobal.setupTopMenu = function () {
	
	// Games Menu Flyout Menu
	$('li.games, ul.list', '#navigationMain').hover(function (){
		
		
		$('li.sub', '#navigationMain').removeClass('fakeHover');
			
		if ($(this).is('li')) {
			$(this).addClass('games_fakeHover');
		} else {
			$(this).addClass('flyout').parent().addClass('fakeHover');

		}
		clearInterval($(this).data('delay'));
		
	}, function (event){
		
		var hovered_menu = $(this);

		// If the user rolled out above the LI, then hide immediately
		if (hovered_menu.is('li') && event.clientY !== undefined) {
			if (event.clientY <= hovered_menu.offset().top){
				hovered_menu.removeClass('games_fakeHover');
				clearInterval(hovered_menu.data('delay'));
				return;
			}
		}


		// Set the delay timer as a data property of the element so each rollover remains
		// independant of each other
		hovered_menu.data('delay', setTimeout(function(){
			hideMenu(hovered_menu);
		}, 700));
		
		
		function hideMenu (hovered_menu) {

			if (hovered_menu.is('li')) {
				hovered_menu.removeClass('games_fakeHover');
			} else{
				hovered_menu.removeClass('flyout').parent().removeClass('fakeHover');
			}
			
			clearInterval(hovered_menu.data('delay'));

		}
		

		
	});	
	
	// Hide all submenus, set style
	$('ul.drop li.sub', '#navigationMain').each(function (i) {
	
		$(this).hover(function () {
			
			var ul = $('ul.drop li:not(:eq(' + i + ')) ul.list', '#navigationMain');
			ul.removeClass('flyout').parent().removeClass('fakeHover');
			
		});
	
	});

	$('li#branding, li.store, li.arcade, li.forum, li.support, li.search', '#navigationWrapper').mouseover(function () {

		$('li.games', '#navigationMain').removeClass('games_fakeHover');
		
	});
	
};

/**
 * Sets up the dynamic styling of all select elements
 */
AtariGlobal.setupSelects = function () {

	// Setup all the dynamic drop downs
	$('select:not(.ignore)').dropdown({
		open: function () {
			//console.info()
		},
		change: function () {
			//console.info(this.selectedIndex);
		}
	});

};

/**
 * Sets up the interactivity of the search input boxes
 * @uses localized_strings
 */
AtariGlobal.setupSearchInput = function () {

	// Setup Search Input
	$('input.searchField').val(localized_strings.menu_label_FindGames).focus(function () {
		var this_el = $(this);
		if (this_el.val() === localized_strings.menu_label_FindGames) {
			this_el.val('');
		}
		this_el.parent().addClass('active');
	}).blur(function () {
		var this_el = $(this);
		if (this_el.val() === '') {
			this_el.val(localized_strings.menu_label_FindGames);
		}
		this_el.parent().removeClass('active');
	});
	
};

/**
 * Styles all the input fields
 */
AtariGlobal.setupInputFields = function () {
	
	
	// create text input fields with custom background
	var wrapperLeftPadding = 5;
	var wrapperLeft, wrapperRight, elementWidth;
	var setupInputFields = function(el){	
		elementWidth = ( $(el).css('width') != 'intrinsic' && $(el).css('width') != 'auto' ) ? $(el).css('width').split('px').join('') : $(el).width();
		wrapperLeft = $('<div class="inputWrapperLeft"></div>').width( elementWidth - wrapperLeftPadding );	
		wrapperRight = $('<div class="inputWrapperRight"></div>');
		$(el).wrap(wrapperLeft).wrap(wrapperRight).css({
			width: '100%',
			visibility: 'visible'
		});
	};	
	// static pages forms
	$('body.static #contentMain form input[type="text"]').each(function(){
		setupInputFields(this);
	});
	// shopping cart forms
	$('body.shopping .wrapper form input[type="text"]').each(function(){
		setupInputFields(this);
	});	
	$('body.shopping .wrapper form input[type="password"]').each(function(){
		setupInputFields(this);
	});
	$('body#homepage div.newsletter form input[type="text"]').each(function () {
		setupInputFields(this);
	});
	$('body#newsletter-register form input[type="text"]').each(function () {
		setupInputFields(this);
	});
	$('body#emai-friend form input[type="text"]').each(function () {
		setupInputFields(this);
	});
	
};

/**
 * Fixes an IE8 issue with form buttons with background image (background shifting on mouse down).
 * 
 * Requires IE8 specific css styles defined in ie8.css.
 */
AtariGlobal.setupFormButtonsIE8 = function(){
	if ($.browser.msie) {
		$("input[type='submit'").mouseover(function(){
			$(this).removeClass('outside');
		}).mouseout(function(){
			$(this).addClass('outside');
		}).focus(function(){
			$(this).addClass('focus');
		});
	}
}

/**
 * Preloads CSS sprites
 */
AtariGlobal.setupPreloadSprites = function () {
	
	preload_image_object = new Image();
	
	// set image url
	image_url = new Array();
	image_url[0] = "/css/assets/sprites/dropdown_top.png";
	image_url[1] = "/css/assets/sprites/dropdown.png";
	
	var i = 0;
	for(i = 0; i <= image_url.length; i++) {
		preload_image_object.src = image_url[i];
	}

};

// Window Utilities ____________________________________________________________

/**
 * TODO: Extend method to accept more parameters (perhaps as an object?)
 * Opens a link in a new browser window, centered on the user's screen
 * @param {Object} url - The link to open
 * @param {Object} windowName - The name of the window
 */
AtariGlobal.openInNewWindow = function (url, windowName, w, h, lbx) {
	
	var winName		= windowName || '';
	if (w == undefined) {
		w = 800;
	}
	if (h == undefined) {
		h = 400;
	}
	if (lbx == undefined) {
		lbx = 1;
	}
	var winl		= (window.screen.width * 0.5) - (w * 0.5);
	var wint		= (window.screen.height * 0.5) - (h * 0.5) - 50; // Visually center the window by subtracting 50px or so
	
	if (lbx) {
		var lightbox;
	//if(!$('#lightbox')){
		
		lightbox = $('<div id="lightbox"></div>');
		
		lightbox.append('<iframe src="'+url+'" width="'+w+'" height="'+h+'" allowTransparency="true" backgroundColor="transparent" scrolling="no" frameborder="0"><p>Your browser does not support iframes.</p></iframe>');

		lightbox.click(function () {
			AtariGlobal.RegisterPopUp.Close();
		});
		
		lightbox.css({
			'padding-top': wint
		});

		$('body').append(lightbox);
		
	} else {
		
		var settings	= 'width='+w+',height='+h+',toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes,top='+wint+',left='+winl;
		
		window.open(url, winName, settings);
	}
	
};

/**
 * Requests the Newsletter Register popup through AJAX
 */
AtariGlobal.RegisterPopUp = function () {

	var lightbox;
	//if(!$('#lightbox')){
		
		lightbox = $('<div id="lightbox"></div>');
		
		lightbox.append('<iframe src="index.php?module=pages&action=register" width="321" height="350" allowTransparency="true" backgroundColor="transparent" scrolling="no" frameborder="0"><p>Your browser does not support iframes.</p></iframe>');

		lightbox.click(function () {
			AtariGlobal.RegisterPopUp.Close();
		});
		
		lightbox.css({
			'padding-top': (window.screen.height * 0.5) - 350
		});

		$('body').append(lightbox);
		
	//}
	
};

/**
 * Requests the Newsletter Register popup through AJAX
 */
AtariGlobal.EmailFriend = function (url, title, discount) {

	var lightbox;
	//if(!$('#lightbox')){
		
		lightbox = $('<div id="lightbox"></div>');
		
		lightbox.append('<iframe src="index.php?module=pages&action=emailfriend&url='+url+'&title='+title+'&discount='+discount+'" width="321" height="350" allowTransparency="true" backgroundColor="transparent" scrolling="no" frameborder="0"><p>Your browser does not support iframes.</p></iframe>');

		lightbox.click(function () {
			AtariGlobal.RegisterPopUp.Close();
		});
		
		lightbox.css({
			'padding-top': (window.screen.height * 0.5) - 304
		});

		$('body').append(lightbox);
		
	//}
	
};

AtariGlobal.RegisterPopUp.Close = function () {
	
	$('#lightbox').remove();
	
};




// Query String Utilities ______________________________________________________

/**
 * Returns the value of a name/value pair in the query string
 * @param {String} variable - Name of the query string variable to retrive
 * @return String value of the specified variable
 */
AtariGlobal.getQueryVariable = function (variable) {
	
	var query	= window.location.search.substring(1);
	var vars	= query.split('&');
	var i		= 0;
	var size	= vars.length;
	var pair	= null;
	
	for (i = 0; i < size; i++) {
		pair = vars[i].split('=');
		if (pair[0] === variable) {
			return pair[1];
		}
	}
	
};






// Cookies _____________________________________________________________________

/**
 * Updates the specified cookie, creating it if it does not yet exist
 * @param {String} cookieName - Name of the cookie to be stored (or overwritten)
 * @param {String} cookieValue - Value to store inside of the cookie
 * @param {Number} expires - Number of days to store cookie on user's machine. 
 * 							 If this is not specified, the cookie will only last 
 * 							 for the duration of the session.
 * @see AtariGlobal.getCookie()
 */
AtariGlobal.setCookie = function (cookieName, cookieValue, expires) {

	var exp = expires || -1; // -1 is used to specify session duration only
	var expiresDate = new Date();
	expiresDate.setTime(expiresDate.getTime() + (1000 * 60 * 60 * 24 * exp));
	
	var myNewCookie = cookieName + '=' + encodeURIComponent(cookieValue) + '; path=/';
	
	if (exp !== -1) {
		myNewCookie =+ '; expires=';
		myNewCookie =+ expiresDate.toGMTString();
	}
	
	document.cookie = myNewCookie;
	
};

/**
 * Gets the value of a cookie, if it exists
 * @param {String} cookieName - Name of cookie to read the value of
 * @return String value of the cookie's value
 * @see AtariGlobal.setCookie()
 */
AtariGlobal.getCookie = function (cookieName) {
	
	var allcookies	= document.cookie;
	var pos			= allcookies.indexOf(cookieName + '=');
	var start		= null;
	var end			= null;
	var value		= null;
	
	if (pos !== -1) {
		
		start	= pos + cookieName.length + 1; // add 1 to include the "=" sign
		end		= allcookies.indexOf(';', start);
		
		if (end === -1) {
			end = allcookies.length;
		}
		
		value = allcookies.substring(start, end);
		value = decodeURIComponent(value);
		
	}
	
	return value;
	
};






// Flash Embedding Utilities ___________________________________________________

/**
 * Utility method for embedding flash content
 * @param {Object} props
 * @return {Object} props
 */
AtariGlobal.embedSWF = function (props) {
	if (typeof($('#' + props.container)[0]) !== 'undefined') {
		var fVersion = props.minFlashVersion || AtariGlobal.min_flash_version;
		swfobject.embedSWF(props.swf, props.container, props.width, props.height, fVersion, this.expressInstall_swf, props.flashvars, props.params, props.attributes);
		return props;
	}
};

/**
 * Provides reference to a Flash movie through SWFObject
 * @param {Object} movieName
 * @return The object for the associated Flash movie
 */
AtariGlobal.getSWF = function (movieName) {
	return swfobject.getObjectById(movieName);
};






// Localization ________________________________________________________________

/* 
param args: array to replace the {n}
example: "Total result count: {0}".localize([10])
*/
/*String.prototype.localize = function (args) {
	var ls = this;
	if (localized_strings[this] != undefined) {
		ls = localized_strings[this];
	}
	if (args) {
		for (var i = 0; i < args.length; i++) {
			ls = ls.replace("{" + i + "}", args[i]);
		}
	}
	return ls + '';
};

Array.prototype.localize = function () {
	for (var i = 0; i < this.length; i++) {
		var ls = this[i];
		if (localized_strings[ls] != undefined) {
			this[i] = localized_strings[ls] + '';
		}
	}
	return this;
};*/






// AJAX for content updates ____________________________________________________

/**
 * AJAX Webservice Switch
 * @param {String} type		- which AJAX service are we running
 * @param {Object} payload	- AJAX parameter bundle
 */
AtariGlobal.WebService = function (type, payload) {
	
	switch (type){
		
		case 'newsletter':
			payload.type = 'POST';
			payload.url = '/ajax/newsletter.php';
			
			break;
		
		case 'storeResults':
			payload.type = 'POST';
			payload.url = '/ajax/storeResults.php';
			
			break;
		
		case 'gameProfile':
			payload.type = 'GET';
			payload.url = '/index.php';

			break;
			
	}
	
	
	AtariGlobal.WebService.AJAX(payload);
	
	
};

/**
 * Globally manages the page updates via Ajax.
 * Fires off the AJAX object with the user defined payload information.
 * @param {Object} payload	- AJAX data options to bind to the jQuery object
 */
AtariGlobal.WebService.AJAX = function (payload) {
	
	var dataType = (payload.dataType !== undefined) ? payload.dataType : 'html';
	
	// jQuery AJAX object
	$.ajax({
		type: payload.type,
		url: payload.url,
		data: payload.data,
		dataType: dataType,
		
		// Global beforeSend wrapper with user defined function
		beforeSend: function () {
	
			// Do global here
			
			if (typeof payload.beforeSend === 'function'){
				payload.beforeSend();
			}
			
		},
		
		// Global success wrapper with user defined function
		success: function (data) {
			
			// Do global here
			
			if (typeof payload.success === 'function') {
				payload.success(data);
			}
			
		}
		
	});
	

};

/**
 * Updates all modules that have been returned by AJAX
 * @param {Object} data
 */
AtariGlobal.WebService.PageUpdate = function (data) {

	// Put the returned HTML in a DIV so jQuery doesn't throw a fuss when trying to traverse it.
	var data = $('<div>').append(data);
			
	data.find('.ajaxModule').each(function () {
		
		var module = $(this);
		var content_id = '#' + module.attr('id');

		$(content_id).replaceWith(module);
		
	});

};




/**
 * Launch Atari !
 */
$(document).ready(function () {
	AtariGlobal.init();	
});


















