/**
 * Sets all advanced functionality for the EA Global Utility Strip (GUS)
 * 
 * Dependencies: jquery-1.2.6.js, jquery.validate-1.5.js, jquery.dynamic-drop.js
 * 
 * @author Kevin Sweeney (Fi)
 * @author Karl Stanton (Fi)
 */

// PROPERTIES __________________________________________________________________
var GUS = {};
GUS.cartCreated = false;
GUS.itemsRemovedFromCart = [];
GUS.minimumAge = 16; // TODO: Make dynamic for localization
GUS.minAgeNotReached = false;

// SHOPPING CART FUNCTIONALITY _________________________________________________

/**
 * Removes all items in the GUS cart (does not empty the DR cart!)
 */
GUS.emptyCart = function () {
				$('#gus_cart tbody tr').remove();
		};

/**
 * Adds change events to all input fields in the GUS cart
 */
GUS.refresh_cart_change_events = function () {
	$('#gus_cart td.quant input').change(function (event) {
		var prodID = $(this).prev('input:hidden').val();
		var amount = $(this).val();
		GUS.changeCartItemQuantity(prodID, amount);
	});
};


/**
 * Creates an HTML element to be placed in the GUS cart
 * 
 * @param {Object} obj
 */
GUS.buildCartNode = function (obj) {
		var brokenImage = (obj.image.indexOf('undefined') !== -1);
	var itemNode = '<tr>\
						<td class="img">';
	
	if (!brokenImage) {
		itemNode += '<img alt="' + obj.title + '" src="' + obj.image + '" class="thumb" />';
	}						
	
	itemNode +=			'</td>\
						<td class="prod">\
							<strong>' + obj.title + '</strong>';
	
	if (obj.platform !== 'none' && typeof(obj.platform) !== 'undefined') {
		itemNode += '<dl>\
						<dt>Platform: </dt>\
						<dd>' + obj.platform + '</dd>\
					</dl>';
	}
	
	itemNode += '</td>\
					<td class="price">' + obj.price + '</td>\
					<td class="quant">\
						<input type="hidden" name="item_' + obj.id + '_productID" value="' + obj.id + '" />\
						<input type="text" name="item_' + obj.id + '_quantity" value="' + obj.quantity + '" />\
					</td>\
					<td class="remove">\
						<a href="javascript:GUS.removeCartItem(' + obj.id + ')">x</a>\
					</td>\
				</tr>';
	
	$('#gus_cart tbody').append(itemNode);
	
		};

/**
 * Adds a single product to the cart
 * @param {Object} productID
 */
GUS.addCartItem = function (productID) {
	var cartItems = [];
	cartItems.push({
		action: 'ADD',
		itemID: productID,
		locale: "en_US",
		quantity: 1,
		extendedAttributes: [
		{
			// This is a hardcoded value for the NOVA Warehouse reporting and is the same across all of the territories.  Please do not change.
			name: 'originSite',
			value: "EACOM"
		}]
	});
	ShoppingCartService.post(GUS.cartSuccess, null, cartItems);
	setOmniValues(this,'o','addToCart','','buyModuleName='+s_ea.pageName+':myModule','successscadd',0,';'+productID);
};

/**
 * Removes a given item from the cart
 * @param {Object} lineItemID
 */
GUS.removeCartItem = function (lineItemID) {
	GUS.changeCartItemQuantity(lineItemID, 0);
	setOmniValues(this,'o','removeProdCart','','','successScRemove',0,';'+lineItemID);
};

GUS.changeCartItemQuantity = function (lineItemID, itemQuantity) {
        var updateInfo = {
               action: 'UPDATE',
               itemID: lineItemID,
               locale: 'en_US',
                quantity: itemQuantity
        };
        if (itemQuantity > 0) {
               // Is this even necessary at all when updating?
               updateInfo.extendedAttributes = [
               {
                       name: 'originSite',
			           value: 'EACOM'
               }];
        }
        ShoppingCartService.post(GUS.cartSuccess, null, [updateInfo]);
}

/**
 * Processes successful add/update responses from the cart service
 * @param {Object} cartJsonData
 */
GUS.cartSuccess = function (cartJsonData) {
		if (ShoppingCartService.hasError()) {
		// Fail silently
	}
	else {
		if (ShoppingCartService.isEmpty()) {
			GUS.emptyCart();
			$('#gus_cart tbody').append("<tr><td colspan='5' align='center'>You have no items in your cart</td></tr>");
			$('#gus_cart_item_count').text(0);
			$('#shopping_cart_subtotal').text('0.00');
		}
		else {
			
			if (typeof(cartJsonData["ns1:AddUpdateShoppingCartResponse"]) !== 'undefined') {
				GUS.updateOrder(cartJsonData["ns1:AddUpdateShoppingCartResponse"], true);
			}
			else if (typeof(cartJsonData["ns1:GetShoppingCartResponse"]) !== 'undefined') {
				GUS.updateOrder(cartJsonData["ns1:GetShoppingCartResponse"], false);
			}
			
		}

	}
	};

/**
 * Handles any failures in the AJAX cart process
 * @param {Object} cartJsonData
 */
GUS.cartError = function (cartJsonData) {
	// Fail silently
};

/**
 * Updates the value of the subtotal displayed in the cart
 */
GUS.updateOrder = function (jsonData, showResult) {
	
	// Clear anything in the cart to be sure that the data matches up 100% with DR cart
	GUS.emptyCart();
	
	// Loop through every product in the DR cart, create a data model to work with,
	// then pass that model into a method that creates and inserts the proper HTML
	// into the GUS cart
	var itemData = jsonData.shoppingCartLineItems;
	
	var quantity_total = 0;
	
	$(itemData).each(function () {
		
		var cartItem = {};
		
		// Attributes
		var cartItemImage;
		var cartItemPlatform;
		
		// Parse Attributes
		$(this.productInfo.attributes).each(function () {
			switch (this.name) {
				case 'eaProdImageSmall':
					cartItemImage = this.value;
					break;
				case 'platform':
					cartItemPlatform = this.value;
					break;
			}
		});
		
		// LineItem ID (referenced by cart)
		cartItem.id = this.key.lineItemID;
		
		// Product ID
		cartItem.prodID = this.productInfo.productKey.productID;
		
		// Quantity
		cartItem.quantity = this.quantity;
		quantity_total += this.quantity;
		
		// Title
		cartItem.title = this.productInfo.baseFields.displayName;
		
		// Platform
		cartItem.platform = cartItemPlatform;
		
		// Price
		cartItem.price = this.productInfo.pricing.formattedUnitPriceWithDiscount;
		
		// Link
		cartItem.link = '#'; // TODO
		
		// Image
		cartItem.image = 'http://drh.img.digitalriver.com/DRHM/Storefront/Company/ea/images/product/small/' + cartItemImage;
		
		// Creates an HTML element based on the data and adds it to the GUS cart
		GUS.buildCartNode(cartItem);
		
	});
	
	// Update total items
	$('#gus_cart_item_count').text(quantity_total);
	
	// Update the subtotal
	$('#shopping_cart_subtotal').text(jsonData.reqLevelPricing.formattedOrderTotal);
	
	// Bind change event listeners to input fields
	GUS.refresh_cart_change_events();
	
	// Show the cart to inform user that something has changed
	if (showResult && ($('#gus_cart div.superdrop').css('display') == 'none')) {
		
		if (GUS.opened_menu) {
			GUS.hideOpenMenu();
		}
		
		GUS.openMenu('gus_cart');
		
	}
	
};

// SETUP _______________________________________________________________________

/**
 * Toggles visibility of GUS dropdown menus
 */
GUS.init_menus = function () {
	
	$(".superdrop > h6 > span > a.btn_close").click(function (event) {
		GUS.hideOpenMenu();
		return false;
	});
	
	var theButton = $('#gus > div.wrapper > div > a.toggle_btn');
	
	theButton.click(function (event) {
		if(this.id != 'signOutLink' && this.id != 'profileLink'){
			var next_menu	= $(this).next('div.superdrop').get(0);
			var tooltip		= $(this).nextAll('div.tooltip').get(0);
			
			// Remove any tooltips once user interacts with menu
			if (tooltip) {
				$(tooltip).remove();
			}
			
			// Toggle menu off or on
			if (!$(this).hasClass('open')) {
			
				// Close the current menu
				if (GUS.opened_menu) {
					$(GUS.opened_menu).prev('a').removeClass('open');
					$(GUS.opened_menu).hide();
				}
				
				// Open the new menu
				GUS.opened_menu = next_menu;
				$(this).addClass('open');
				$(GUS.opened_menu).addClass('open');
				$(GUS.opened_menu).show();
				
				/*
				 In the case where the cart is opened we fire an omniture call
				*/
				if($(this).id = 'gus-cart-btn'){
					setOmniValues(this,'o','viewCart','','','successcartview',0,'','');
				}
				
				// Close menu if user clicks anywhere else on the page
				$(document).click(function (event) {
					if (!$(event.target).parents('.superdrop').hasClass('open') && GUS.opened_menu) {
						GUS.hideOpenMenu();
					}
				});
				
			}
			else {
				GUS.hideOpenMenu();
			}
			
			// Prevent hyperlink from being followed
			return false;
		}
	});

};



/**
 * Applies close functionality to any displayed tooltips
 */
GUS.init_tooltips = function () {
	$('div.tooltip a.close').click(function (event) {
		$(this).parent().hide();
		event.preventDefault();
	});
};

/**
 * Wires up Fi version of cart with Digital River's. Whenever DR's cart is updated,
 * an event is dispatched to the GUS cart, instructing it to update.
 */
GUS.init_cart = function () {
	
	// Intialize the cart service
	ShoppingCartService.init({
		siteID: "ea",
		locale: "en_US",
		serverName: 'eastore.ea.com',
		endpoint: '/integration/job/request/ShoppingCartService/ea/site/',
		fieldsToBeReturned: {
			baseFields: ['displayName'],
			attributes: ['platform','eaProdImageSmall']
		}
	});
	
	// Set currency code to use
	ShoppingCartService.setCurrencyCode("USD");
	
	// Get the contents of the cart if it isn't empty
	ShoppingCartService.post(GUS.cartSuccess, GUS.cartError, []);
	
	/**
	 * @deprecated - This link is now just specified in the href attribute of the button
	 */
	//$('#gus_cart fieldset.checkout a.submitBtn').click(function (event) {
		//$('#dr_scs_cart_buttons_wrapper a').click(); // TODO: New submission behavior
		//window.location.href = 'http://eastore.ea.com/store/ea/cart'; // Cart
		//window.location = 'https://eastore.ea.com/store/ea/DisplayThreePgCheckoutAddressPaymentInfoPage'// Checkout Page
	//});
	
};

/**
 * Applies validation functionality to selected forms and form inputs
 */
GUS.init_forms = function () {
	
	var currentDate	= new Date();	// Should this be set globally via server instead of relying on user's machine?
	
	$('#gus form a.submitBtn').click(function (event) {
		$(this).parents('form').submit();
		return false;
	});
	
	$('#login_form_forgot').click(function (event) {
		$('#gus_reminder').show();
		$('#login_form').hide();
		return false;
	});
	$('#login_form_return').click(function(){
		$('#gus_reminder').hide();
		$('#login_form').show();
		return false;
	});
	
	// Events
	$("#login_form").keypress(function(e){
		if(e.which == 13){
			$(this).submit();
		}
	});
	$("#register_form").keypress(function(e){
		if(e.which == 13){
			$(this).submit();
		}
	});
	$("#reminder_form").keypress(function(e){
		if(e.which == 13){
			$(this).submit();
		}
	});
	
	// Check for existence of jQuery Pre-Text plug-in
	$('#gus_login input[type="text"], #gus_register input[type="text"], #gus_login input[type="password"], #gus_register input[type="password"]').labelinput();
	
	
	// Rollovers for input boxes
	$("#gus form div.inputWrapper input").hover(
		function(){
			resetInputs();
			if(!$(this).parent().hasClass("inputWrapper_error")) $(this).parent().addClass("inputWrapper_hover");
		},
		function(){
			resetInputs();
			if(!$(this).parent().hasClass("inputWrapper_error")) $(this).parent().addClass("inputWrapper");		
		}
	).focus(function(){
		resetInputs();
		if(!$(this).parent().hasClass("inputWrapper_error")) $(this).parent().addClass("inputWrapper_active");
	});
	
	// Resets all input boxes
	resetInputs = function(){
		$("#gus form div.inputWrapper").removeClass("inputWrapper_hover").removeClass("inputWrapper_active").addClass("inputWrapper");
	}
	
	// Checks for existence of jQuery Dyanmic Drop Down plug-in
	if($.fn.dropDown){
		// Registration Form
		$("#register_form_country").dropDown({
			css: 'drop-game',
			width: 175,
			defaultheight: 200,
			timeout: 4000
		});
		// Age
		$("#register_form_dob_month").dropDown({
			css: 'drop-register-month',
			width: 113,
			defaultheight: 140,
			timeout: 4000
		});
		$("#register_form_dob_day").dropDown({
			css: 'drop-register-dayyear',
			width: 68,
			defaultheight: 140,
			timeout: 4000
		});
		$("#register_form_dob_year").dropDown({
			css: 'drop-register-dayyear',
			width: 68,
			defaultheight: 140,
			timeout: 4000
		});		
		// Game Browser Review List (Up to a maximum of 6)
		var drops = "#game_browser_reviewlist_1";
		for(var i=2;i<=6;i++){
			drops = drops + ", #game_browser_reviewlist_"+i;
		}
		$(drops).dropDown({
			css: 'drop-default',
			width: 142,
			defaultheight: null,
			timeout: 4000
		});
	}
	
	$("#register_form_country").change(function(){
		if($(this).val()!="us") {
			if ($("input#register_thirdPartyOptIn").attr("checked") == true) {
				$("input#register_thirdPartyOptIn").attr("checked", false);
				$("input#register_thirdPartyOptIn").trigger("change");
				
			}
			if ($("input#register_globalOptIn").attr("checked") == true) {
				$("input#register_globalOptIn").attr("checked", false);
				$("input#register_globalOptIn").trigger("change");
				
			}
		} 
	});
	
	// Checkboxes
	if($.fn.checkbox){
		$("#login_form_remember, #register_globalOptIn, #register_form_tos, #register_remember_me, #register_thirdPartyOptIn").checkbox();
	}
	
	// Checks for existence of jQuery Validate plug-in
	if ($.fn.validate) {
		
		/**
		 * Adds check for users under 13
		 * 
		 * @param {Object} value
		 * @param {Object} element
		 * @param {Object} params {year, month, day, minAge}
		 */
		jQuery.validator.addMethod('minimumage', function (value, element, params) {
			
			var ofMinAge;
			
			var y = $('#' + params.formId + ' .f_year').val();
			var m = $('#' + params.formId + ' .f_month').val();
			var d = $('#' + params.formId + ' .f_day').val();
			
			var msPerYear = 3.1556926 * (Math.pow(10, 10));
			var birthDate = new Date(y, m, d);
			var age = (currentDate.getTime() - birthDate.getTime()) / msPerYear;
			
			if (age >= params.minAge) {
				ofMinAge = true;
			}
			else {
				GUS.minAgeNotReached = true;
				ofMinAge = false;
			}
			
			return this.optional(element) || ofMinAge;
			
		},
		'You are not old enough');
		
		// Login Form Validation
		if ($('#login_form').length > 0) {
			
			this.val_login = $('#login_form').submit(function(){
				return false;
			}).validate({
				onfocusout: false,
				onkeyup: false,
				onclick: false,
				submitHandler: function(form){
					$.ajax({
						type: 'POST',
						url: "/login/login",
						data: $(form).serialize(),
						beforeSend: function(){
							$("#login_form > .formSubmit > .btn_simple").hide();
							$("#login_loader").show();
							GUS.rememberPath();
						},
						success: function(html){
							if (html == '1') {
								setOmniValues(this,'0',s_ea.pageName+':'+'sucessfulLogin','','','logins',0,'','','');
								if (window.location.href.indexOf('/tips') !== -1) {
									if (window.location.href.indexOf('?') !== -1) {
										if (window.location.href.indexOf('login=true') == -1) {
											window.location.href = window.location.href + '&login=true';
										} else {
											window.location.reload(true);
										}
										
									} else {
										window.location.href = window.location.href + '?login=true';
									}
							        
								} else {
									window.location.reload(true);
								}
								
							}
							else {
								omniLinkCall(this,'loginError');
								$('#gus_login div.superdrop .error_msg_box').html(html).show();
								$("#login_form > .formSubmit > .btn_simple").show();
								$("#login_loader").hide();
							}
						},
						error: function(){
							$("#login_form > .formSubmit > .btn_simple").show();
							$("#login_loader").hide();
						}
					});
				},
				highlight: function(element, errorClass){
					$(element).addClass('inputWrapper_error');
					$(element).parent('.inputWrapper').removeClass('inputWrapper').addClass('inputWrapper_error');
					if ($(element).attr('id') === 'login_form_password') {
						setTimeout("$('#login_form_password').parent().removeClass('inputWrapper').addClass('inputWrapper_error')", 10);
					}
				},
				unhighlight: function(element, errorClass){
					$(element).removeClass('inputWrapper_error');
					$(element).parent('.inputWrapper_error').removeClass('inputWrapper_error').addClass('inputWrapper');
					if ($(element).attr('id') === 'login_form_password') {
						setTimeout("$('#login_form_password').parent().removeClass('inputWrapper_error').addClass('inputWrapper')", 10);
					}
				},
				groups: {
					login: 'login_form_email login_form_password'
				},
				errorElement: 'em',
				errorLabelContainer: "#login_form > .error_msg_box",
				errorPlacement: function(error, element){
					if (element.attr('name') == 'login_form_email' || element.attr('name') == 'login_form_password') {
						error.insertAfter('#login_form_remember');
					}
					else {
						error.insertAfter(element);
					}
				},
				rules: {
					login_form_email: {
						required: true,
						email: true
					},
					login_form_password: {
						required: true
					}
				},
				messages: {
					login_form_email: {
						required: "Invalid e-mail",
						email: "Invalid e-mail address format"
					}
				}
			});
			
		}
		
		// Password Reminder Form Validation
		if ($('#reminder_form').length > 0) {
			
			this.val_reminder = $('#reminder_form').submit(function(){
				return false;
			}).validate({
				onfocusout: false,
				onkeyup: false,
				onclick: false,
				submitHandler: function(form){
					$.ajax({
						type: 'POST',
						url: "/login/forgotPassword",
						data: $(form).serialize(),
						success: function(html){
							$('#gus_reminder_success').html(html).show();
							$('#gus_reminder').hide();
							$('#gus_login_back').click(function(){
								$('#gus_reminder').hide();
								$('#gus_reminder_success').hide();
								$('#login_form').show();
								return false;
							});
						}
					});
				},
				highlight: function(element, errorClass){
					$(element).addClass('inputWrapper_error');
					$(element).parent('.inputWrapper').removeClass('inputWrapper').addClass('inputWrapper_error');
				},
				unhighlight: function(element, errorClass){
					$(element).removeClass('inputWrapper_error');
					$(element).parent('.inputWrapper_error').removeClass('inputWrapper_error').addClass('inputWrapper');
				},
				errorElement: 'em',
				errorLabelContainer: "#reminder_form > .error_msg_box",
				errorPlacement: function(error, element){
					error.insertAfter(element);
				},
				rules: {
					reminder_form_email: {
						required: true,
						email: true
					}
				},
				messages: {
					reminder_form_email: {
						required: "Invalid e-mail",
						email: "Invalid e-mail address format"
					}
				}
			});
			
		}
		
		// Registration Form Validation
		if ($('#register_form').length > 0) {
			
			this.val_register = $('#register_form').submit(function(){
				return false;
			}).validate({
				onfocusout: false,
				onkeyup: false,
				onclick: false,
				submitHandler: function(form){
					$("#registration_error").hide();
					$.ajax({
						type: 'POST',
						url: "/login/registration",
						data: $(form).serialize(),
						beforeSend: function(){
							$("#register_form > .formSubmit > .btn_register").hide();
							$("#registration_loader").show();
							GUS.rememberPath();
						},
						success: function(html){
							//reset form before hiding, in case it needs to be reshown
							$("#register_form > .formSubmit > .btn_register").show();
							$("#registration_loader").hide();
							
							//hide form and place success html after it
							$('#gus_register div.superdrop div.inner > form').hide().after(html);
						},
						error: function(){
							$("#register_form > .formSubmit > .btn_register").show();
							$("#registration_loader").hide();
						}
					});
				},
				highlight: function(element, errorClass){
					$(element).addClass('inputWrapper_error');
					$(element).parent('.inputWrapper').removeClass('inputWrapper').addClass('inputWrapper_error');
				},
				unhighlight: function(element, errorClass){
					$(element).removeClass('inputWrapper_error');
					$(element).parent('.inputWrapper_error').removeClass('inputWrapper_error').addClass('inputWrapper');
				},
				groups: {
					dob: 'register_form_dob_year register_form_dob_month register_form_dob_day',
					pw: 'register_form_password register_form_password_confirm'
				},
				errorElement: 'em',
				errorPlacement: function(error, element){
					if (element.attr('name') == 'register_form_dob_year' || element.attr('name') == 'register_form_dob_month' || element.attr('name') == 'register_form_dob_day') {
						error.insertAfter('#register_form_dob_year');
					}
					else 
						if (element.attr('name') == 'register_form_password' || element.attr('name') == 'register_form_password_confirm') {
							error.insertAfter('#register_form_password_confirm');
						}
						else 
							if (element.attr('name') == 'register_form_tos') {
								error.insertAfter('a.terms');
							}
							else {
								error.insertAfter(element);
							}
				},
				rules: {
					register_form_email: {
						required: true,
						email: true
					},
					register_form_password: {
						required: true,
						minlength: 6
					},
					register_form_password_confirm: {
						required: true,
						equalTo: '#register_form_password'
					},
					register_form_dob_month: {
						required: true,
						minimumage: {
							formId: 'register_form',
							minAge: GUS.minimumAge
						}
					},
					register_form_dob_day: {
						required: true,
						minimumage: {
							formId: 'register_form',
							minAge: GUS.minimumAge
						}
					},
					register_form_dob_year: {
						required: true,
						minimumage: {
							formId: 'register_form',
							minAge: GUS.minimumAge
						}
					},
					register_form_tos: {
						required: true
					}
				
				},
				messages: {
					register_form_email: {
						required: "Required field",
						email: "Invalid e-mail address format"
					},
					register_form_password: {
						required: "Required field",
						minlength: "Password must be &gt;6 characters"
					},
					register_form_password_confirm: {
						required: "Required field",
						equalTo: "Passwords do not match"
					},
					register_form_dob_month: {
						required: "Required field",
						minimumage: ''
					},
					register_form_dob_day: {
						required: "Required field",
						minimumage: ''
					
					},
					register_form_dob_year: {
						required: "Required field",
						minimumage: ''
					},
					register_form_tos: {
						required: "You must agree to the terms"
					}
				},
				invalidHandler: function(form, validator){
					var errors = validator.numberOfInvalids();
					if (errors !== null) {
						var message = errors == 1
				 ? "You missed 1 field."
				 : "You missed ' + errors + ' fields.";
						//var message = "Sorry, you do not meet the criteria for registration.<br />Please correct any invalid fields to proceed.";
					
						if (GUS.minAgeNotReached) {
							message = "Sorry, you do not meet the criteria for registration.";
							message += "<br />Go <a href=\"#\" onClick=\"javascript:GUS.registerReturn();\">back</a> to registration form.";
							$("#register_form").hide();
							$("#age_registration_error").html(message).show();
						} else {
							$("#registration_error").html(message).show();
						}
						
					}
					else {
						$("#registration_error").hide();
					}
				}
			});
			
		}
	}
};

// MENU CONTROLS _______________________________________________________________

GUS.registerReturn = function() {
	$("#age_registration_error").hide();
	$("#register_form").show();
	return false;
}

/**
 * Closes any open GUS "superdropdowns"
 */
GUS.hideOpenMenu = function () {
	
		
	$(GUS.opened_menu).prev('a').removeClass('open');
	$(GUS.opened_menu).hide();
	
	if ($('#gus_modal_window').length > 0) {
		$('#gus_modal_window').remove();
	}
	
	//$(document).unbind('click');
	
	GUS.opened_menu = null;
		
	try{
		this.val_login.resetForm();
		this.val_reminder.resetForm();
		this.val_register.resetForm();
	}catch(e){	}
	
};

/**
 * Opens a specific menu in the GUS
 * 
 * @param {String} menu_id - The ID of the menu to open
 * @param {Boolean} modal - Whether the popup should trigger a modal window (ie, create a transparent overlay behind it)
 */
GUS.openMenu = function (menu_id, modal) {
	
	var m = modal || false;
	$('#' + menu_id + ' a.toggle_btn').trigger('click');
	
	if (m === true) {
		$('body').append('<div id="gus_modal_window">&nbsp;</div>');
		$('#gus_modal_window')
		.css({
			'z-index': '999',
			'text-align': 'left',
			'position': 'fixed',
			'top': '0px',
			'left': '0px',
			'height': '100%',
			'width': '100%'
		})
		.css('background-color', '#000000')
		.css('opacity', '0.6');
	}
	
	/*
	Special cart related omniture handling
	*/
	if(GUS.cartCreated == false){
		GUS.cartCreated = true;
		setOmniValues(this,'o','createCart','','','successscopen',0,'','');
	}
};


/**
 * Allows a menu to be open temporarily (without becoming the active menu)
 * 
 * @param {String} menu_id - The string identifier for the particular GUS item
 * @param {Number} duration - Amount of time (in milliseconds) to display menu
 * @param {Function} callback_function - Function that will execute once the menu is fully hidden
 */
GUS.tempMenuOpen = function (menu_id, duration, callback_function, modal) {
	
	var temp_btn	= $('#' + menu_id + ' a.toggle_btn').get(0);
	var temp_menu	= $('#' + menu_id + ' div.superdrop').get(0);
	
	$(temp_btn).addClass('open');
	$(temp_menu).addClass('open');
	$(temp_menu).show();
	
	setTimeout(function () {
		$(temp_btn).removeClass('open');
		$(temp_menu).removeClass('open');
		$(temp_menu).fadeOut(200, callback_function);
	}, duration);
	
};

// Instantiate GUS once DOM is fully ready
$(document).ready(function () {

	//var showGUSLocalizationScreen = true;
	GUS.init_menus();
	GUS.init_tooltips();
	GUS.init_cart();
	GUS.init_forms();
	
	// Tweak height of Terms of Service
	if (navigator.appVersion.indexOf("Win")!== -1 && $.browser.safari) {
		$('#register_form #tacContainer .content p').css('height', '50px'); // Windows Safari
	}
	else if (navigator.appVersion.indexOf("Mac")!== -1) {
		$('#register_form #tacContainer .content p').css('height', '59px'); // Any Macintosh browsers
	}
	
	
	if (typeof(openSigninMenu) !== 'undefined') {
		GUS.openMenu('gus_login', false);
	}
	
	
	/**
	 * Wire up localization links to refresh page
	 */
	$('#gus_localization ul.territories a.flag').click(function () {
		redirectDefaultLocationURL($(this).attr("href"));
		return false;
	});
	 
	/**
	* The following functionality will display / hide the country selector.
	*/
	if (typeof(showGUSLocalizationScreen) !== 'undefined') {
		if (showGUSLocalizationScreen){
			GUS.openMenu('gus_localization', true);
		} else {
				}
	}
});

/**
 * My first attempt ever at ajax!
 */
GUS.displayTerms = function () {
	$(document).scrollTop(0);
	// Ajax call
	$.ajax({
		type: 'GET',
        url: "/gus/terms",
        dataType: 'html',

		success: function (html) {
			//$("#ajax-loader").remove();
			
			// Put the returned HTML in a DIV so jQuery doesn't throw a fuss
			// when trying to traverse it.
			var el = $('<div>').append(html);

			
			$('#tacContainer').html(el.find('#tacContainer').html());
			
			$("#tacContainer").children().show();
		}
		
	});
	
};

GUS.rememberPath = function () {
	//alert($("#netoframe").length);
	if ($("#netoframe").length > 0) {
	    //document.cookie = 'tipsPath=' + escape($("#netoframe").attr('src')) + ';';
	    document.cookie = 'tipsPath=' + escape(window.frames["netoframe"].location.href) + ';';
	}
	
}

if (document.forms.register_form) {
	//alert('');
	//GUS.displayTerms();

	// Tweak height of Terms of Service
	if (navigator.appVersion.indexOf("Win")!== -1 && $.browser.safari) {
		$('#register_form #tacContainer .content p').css('height', '50px'); // Windows Safari
	} else if (navigator.appVersion.indexOf("Mac")!== -1) {
		$('#register_form #tacContainer .content p').css('height', '59px'); // Any Macintosh browsers
	}

}