// Function used to display loading box
function showLoadingBox(eleRef, totalElements, totalRecords)
{
	document.getElementById("loadingBox").style.height = window.document.body.clientHeight;
	document.getElementById("loadingBox").style.width = window.document.body.clientWidth;
	document.getElementById("loadingBox").style.display = "block";

	window.setTimeout("changeSelects(document.getElementById('" + eleRef.id + "'), " + totalElements + ", "
						+ totalRecords + ")", 2000);
}

// Function used to hide loading box
function __hideLoadingBox()
{
	document.getElementById("loadingBox").style.display = "none";
}

// Funtion used same as PHP's in_array
function inArray(theNeedle, theHaystack)
{
	// Loop through given array
	for (var i in theHaystack)
	{
		// If given value is present in given array then return true
		if (theHaystack[i] == theNeedle)
		{
			return true;
		}
	}

	// If given value is not present in given array then return false
	return false;
}




// Function used to display loading box
function showLoadingBoxForAjax()
{
	document.getElementById("loadingBox").style.height = window.document.body.clientHeight + "px";
	document.getElementById("loadingBox").style.width = window.document.body.clientWidth + "px";
	document.getElementById("loadingBox").style.display = "block";
}

// Function used to hide loading box
function hideLoadingBoxForAjax()
{
	document.getElementById("loadingBox").style.display = "none";
}


// display activities popup menu
function displaySubmenu(objId)
{
  obj = document.getElementById(objId);
  obj.style.display = 'block';
}

// hide activities popup menu
function hideSubmenu(objId)
{
  obj = document.getElementById(objId);
  obj.style.display = 'none';
}

// Function used to open virtual window
function openVirtualWindow(eleId, ajaxIndicator)
{
	// Element reference which is virtual window
	eleRef = document.getElementById(eleId);

	// Show element and AJAX indicator in it
	eleRef.style.display = "block";
	eleRef.innerHTML = '<img src="' + ajaxIndicator + '" />';
}

// Function used to close virtual window
function closeVirtualWindow(eleId)
{
	// Hide element
	document.getElementById(eleId).style.display = "none";
}

// Function used to make virtual window draggable
function makeDraggable(eleId)
{
	// Element reference which is virtual window
	eleRef = document.getElementById(eleId);

	// Get IFRAME's reference
	ie_iframe = document.getElementById(eleId + "_iframe");

	// Make virtual window draggable
	new Draggable(eleId, {
		change: function(instance) {
			// Adjust IFRAME as per virtual window
			__adjustIframe(eleRef, ie_iframe);
		}
	});

	// Adjust IFRAME as per virtual window
	__adjustIframe(eleRef, ie_iframe);
}

// Function used to adjust IFRAME as per virtual window
function __adjustIframe(virtualWindow, iframeWindow)
{
	// If IFRAME exists
	if (undefined != iframeWindow)
	{
		// Adjust IFRAME properties as per virtual window
		iframeWindow.style.top = virtualWindow.offsetTop + "px";
		iframeWindow.style.left = virtualWindow.offsetLeft + "px";
		iframeWindow.style.width = virtualWindow.clientWidth + "px";
		iframeWindow.style.height = virtualWindow.clientHeight + "px";
	}
}

// Function to create an inplace input file editor
function setupAjaxFileInput(el, url, options)
{
	var editor = new Ajax.InPlaceEditor(el, url, options);
	Object.extend
	(
		editor,
		{
			createEditField: function()
			{
				var obj = this;
				this.options.textarea = false;
				var textField = document.createElement("input");
				textField.obj = this;
				textField.type = "file";
				textField.name = this.element.id;
				textField.value = "";
				textField.style.backgroundColor = this.options.highlightcolor;
				textField.className = 'editor_field';
				this.editField = textField;
				this.form.encoding = "multipart/form-data";
				this.form.target = 'hidden_iframe';
				this.form.method = 'post';
				this.form.action = this.url;
				this.form.appendChild(this.editField);
			}
		}
	);
	Object.extend
	(
		editor,
		{
			onSubmit: function() {
				return true;
			}
		}
	);
	return editor;
}



// Workaround for Internet Explorer not fully suporting the :hover pseudo class
// See http://www.htmldog.com/articles/suckerfish/dropdowns/
/*
sfHover = function()
{
	var sfEls = document.getElementById("header_links").getElementsByTagName("LI");
	for (var i = 0; i < sfEls.length; i ++)
	{
		sfEls[i].onmouseover = function()
		{
			this.className += " sfhover";
		}
		sfEls[i].onmouseout=function()
		{
			this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent)
{
	window.attachEvent("onload", sfHover);
}
*/

// Function used to attach onclick event to expander images
function attach_onclick_to_expanders(context)
{
	if ( ! context )
	{
		context = document;
	}

	// Add onclick event for expander images
	jQuery("img.expanderImage", context).bind("click", expand_collapse);
}

// Function used to handle onclick event for expander image
function expand_collapse()
{
	// Get unique id for expander image
	var callingElement = get_element_reference(this);
	var expander = jQuery(callingElement);
	var expander_image_id = callingElement.id.replace("expanderImage_", "");

	// If table row is closed
	if (expander.is(".closed"))
	{
		// Change expander image's SRC
		callingElement.src = callingElement.src.replace("plus", "minus");

		// Open table row
		jQuery("#tr_"+expander_image_id).show();

		// Change expander image's class
		expander.removeClass("closed").addClass("opened");
	}
	// Default case
	else
	{
		// Change expander image's SRC
		callingElement.src = callingElement.src.replace("minus", "plus");

		// Hide table row
		jQuery("#tr_"+expander_image_id).hide();

		// Change expander image's class
		expander.removeClass("opened").addClass("closed");
	}
}

// Function used to attach onclick event to expander images
function attach_onclick_to_expanders_class(context)
{
	if ( ! context )
	{
		context = document;
	}

	// Add onclick event for expander images
	jQuery("img.expanderImage", context).bind("click", expand_collapse_class);
}

// Function used to handle onclick event for expander image
function expand_collapse_class()
{
	// Get unique id for expander image
	var callingElement = get_element_reference(this);
	var expander = jQuery(callingElement);
	var expander_image_id = callingElement.id.replace("expanderImage_", "");

	// If table row is closed
	if (expander.is(".closed"))
	{
		// Change expander image's SRC
		callingElement.src = callingElement.src.replace("plus", "minus");

		// Open table row
		jQuery(".tr_"+expander_image_id).show();

		// Change expander image's class
		expander.removeClass("closed").addClass("opened");
	}
	// Default case
	else
	{
		// Change expander image's SRC
		callingElement.src = callingElement.src.replace("minus", "plus");

		// Hide table row
		jQuery(".tr_"+expander_image_id).hide();

		// Change expander image's class
		expander.removeClass("opened").addClass("closed");
	}
}

// Function used to get element's reference
function get_element_reference(eleRef)
{
	// If internet explorer
	if (window.event)
	{
		return window.event.srcElement;
	}

	// Return default value
	return eleRef;
}



/**
 * Delete a row from a grid.
 *
 * @param gridId The id of the grid to delete.
 * @param rowId The id of the row in the grid to delete.
 */
function deleteGridRow(gridId, rowId)
{
  grids[gridId].deleteRow(rowId);
}


/**
 *  Runs the jQuery dom_update for us.
 */
function dom_update()
{
	jCake.triggerGlobalEvent('domUpdated', [document]);
}


/**
 * Handles validation errors from the in-place editors and when saving a form. To generate an
 * error, simply pass an JSON object back from the AJAX call. If the JSON object has a parameter
 * named "error_message" that will be displayed. TODO: If it has an object named "error_elements"
 * it will take the keys as DOM id's and the value as an error message for that value.
 *
 * @access public
 * @param error Error object passed via JSON, or empty if no errors.
 * @param element For saves against a single DOM element (such as in-place editors), this is the
 *        DOM element that was saved.
 * @return boolean True if there are no errors
 *
 */
function handleValidationErrors(error, element)
{
	if ( ! error )
	{
		displayMessage( 'Server error.');
	}

	if ( isErrorObject( error ) )
	{
		if ( 'object' == typeof(element) )
		{
			// And higlight the field with the error so the user knows something is wrong.
			Element.addClassName(element, 'input_error');
		}

		// Display the error message.
		// Must be called last in this sequence or the user may see the JSON message.
		displayMessage(error.error_message);
		return false;
	}


	// Since there is no JSON object, we made a successful save. Lets clear out the message area.
	clearMessageArea();

	if ( 'object' == typeof(element) )
	{
		// Lets remove the input_error highlighting.
		Element.removeClassName(element, 'input_error');
	}
	return true;
}

/**
 * Checks an object (probably returned in AJAX via JSON) and reports if it is an error object or not.
 *
 * @access public
 * @param error Object the object to check
 * @return True if the object has properties of an error object.
 */
function isErrorObject( error )
{
	// If error isn't an object, it can't be an error object.
	if( error instanceof Object )
	{
		// error_message is one of the properties of an error object.
		if( 'undefined' != typeof(error.error_message) )
		{
			return true;
		}

		// error_elements is an optional property for error objects.
		if( 'undefined' != typeof(error.error_elements) )
		{
			return true;
		}
	}

	// Either not an objet, or an object but doesn't have any error properties.
	return false;
}

/**
 * Returns the layout's messagearea.
 */
function getMessageArea()
{
	// get the message area
	var messagearea = document.getElementById('messagearea');

	// If there isn't a message area in this page check if we are in an iframe, and get the parent's
	// message area if we can
	if( ! messagearea )
	{
		messagearea = window.parent.document.getElementById('messagearea');
	}

	return messagearea;
}


/**
 * Put a message in the layout's messagearea, or if there isn't once, display in an alert().
 *
 * @param string Message
 */
function displayMessage(message)
{
	// find the messagearea for this page, if there is one.
	/* TODO: for now always alert() the message
	var messagearea = getMessageArea();

	if ( messagearea )
	{
		// if there is a messagearea, display the error there
		messagearea.innerHTML = message.escapeHTML();
	}
	else
	*/
	{
		// if there is no messagearea, display the message in an alert box.
		alert(message);
	}
}


/**
 * Clear the message area.
 */
function clearMessageArea()
{
	// find the messagearea for this page, if there is one.
	var messagearea = getMessageArea();

	if ( messagearea )
	{
		// clear the message area
		messagearea.innerHTML = '';
	}
}

/**
 * Show the spinner.
 *
 * @param element The element which triggered the need for the spinner.
 */
function showSpinner(element)
{
	$('loadingBox').show();
}


/**
 * Hide the spinner.
 *
 * @param element The element which originally triggered the need for the spinner.
 */
function hideSpinner(element)
{
	$('loadingBox').hide();
}




jQuery(document).ready(function()
{
	
	/*
	 * Code for collapsible boxes.
	 */
	// find all collapsible images
	jQuery('a.collapsible').click( function()
	{
		id = this.id.replace(/_image/, '');

		// toggle the display of the corresponding content box which clicked
		var display = jQuery('#' + id + '_content').toggle()[0].style.display;

		// and change the image as appropriate
		var box_mode = ( 'block' == display ) ? 'open' : 'closed';
		jQuery('#' + id + '_image img').attr( 'src', jCake.url( '/img/box-' + box_mode + '.png' ) );
		jQuery('#' + id ).html( '[' + jQuery('#' + id ).attr(box_mode + 'Text') + ']' );
	});


	// make sure bug report link will generate a popup
	/*
	var bug_report_link = jQuery('#bug_report_link');
	jCake.triggerGlobalEvent('domUpdated', bug_report_link);
	*/

	/*
	 * Allow search button to open in new window
	 */
	jQuery('input#search_new_tab_button').click( function()
	{
		jQuery('form#search_form').attr('target', '_blank');
		return true;
	});
	jQuery('input#search_same_tab_button').click( function()
	{
		jQuery('form#search_form').removeAttr('target');
		return true;
	});
	
	jQuery('.helpIcon').hover(showHelp, hideHelp);
	
	// Allow paypal site status button to open new site in a new window
	jQuery('a[href="/admin/status"]').attr('href', 'https://www.x.com/community/ppx/system_status/mts_updates?view=overview').attr('target', '_blank');
	
	if(jCake.vars.auto_logout){
		/*
		 * check to make sure that we have a valid email address that we can deal with
		 * if we do, then check for new email every 300 seconds
		 */
		webmail.isValidEmail();
	

		setTimeout(autoLogOut, 1200000);
	}
	
});

function autoLogOut(){
	shouldLogout = false;
	jQuery.ajax({
		type: "GET"
		, url: '/users/should_log_out'
		, dataType: 'json'
		, success: function(result){
			shouldLogout =  result.shouldLogOut;
			if(shouldLogout){
				window.location = '/users/logout';
			}else{
				setTimeout(autoLogOut, 1200000);
			}
			
		}
	});
	return;
	
}

function showHelp() {
	jQuery('div#' + this.id + 'Div').fadeIn('slow');
}

function hideHelp() {
	jQuery('div#' + this.id + 'Div').fadeOut('slow');
}


/**
 * This method is used by display_entity element to update years in business span
 * This method is used to update years in business span with new calculated value.
 *
 * @access public
 */
function updateYearsInBusiness(request)
{
	// Force editor to leave mode (our job since we're on callback)
	editorYearsInBusiness.leaveEditMode();

	// Get the value from year established span
	var year_established = jQuery.trim(jQuery("#year_established").html());

	if (year_established) {
		// Get current date's object
		var current_date = new Date();

		// Get current year
		var current_year = current_date.getFullYear();

		// Calculate years in business
		var years_in_business = current_year - parseInt(year_established);

		// Executes only if year_in_business is greater then zero
		if (0 < years_in_business)
		{
			// Update the years in business span with new calculated value.
			jQuery("#years_in_business").show()
			jQuery.trim(jQuery("#years_in_business").html("&nbsp;&nbsp;&nbsp;&nbsp;" + years_in_business + " Years"));
		}
	}

	return true;
}

/**
 * This method is used to hide the span for 'Years_in_business' whille editing the 'year Est'
 *
 * @access public
 *
 */
function hideYearsInBusiness()
{
	jQuery("#years_in_business").hide();
}

/**
 * Function to show the loading spinner for pagination
 */
function show_pagination_loading()
{
	// Create the popup instance to show processing message
	var PaginationPopup = new PopupWindow('pagination');
	PaginationPopup.displayActivityIndicator('Loading...', true);
}

/**
 * Function to hide the loading spinner for pagination
 */
function hide_pagination_loading()
{
	// Create the popup instance
	var PaginationPopup = new PopupWindow('pagination');
	// Close the popup
	PaginationPopup.close();
}




// View cart
function view_cart(opportunity)
{
	jQuery.getJSON('/sales/preview_codes/'+opportunity, {}, function(data)
	{
		if (data.PreviewCode.length == 0)
		{
			alert('Could not find cart');
		}
		else if (data.PreviewCode.length == 1)
		{
			window.open('/preview_codes/enter/'+data.PreviewCode[0].code+'/agent/cart');
		}
		else
		{
			var url = '/sales/view_cart';
			jQuery.each(data.PreviewCode, function(i)
			{
				url += '/' + data.PreviewCode[i].code;
			});
			jQuery().jPopup({
				title: 'Go To Cart'
				, url: url
				, width: 350
				, height: 300
			});
		}
	});

	return false;
}

// Function used to edit an address in a popup
function editAddress(self, fn, container, multiLine, typeId, contactId, orderItemId)
{
	if (typeof container == 'undefined' || !container)
	{
		container = null;
	}

	if (typeof multiLine == 'undefined' || !multiLine)
	{
		multiLine = false;
	}

	if (typeof typeId == 'undefined' || !typeId)
	{
		typeId = null;
	}

	if (typeof contactId == 'undefined' || !contactId)
	{
		contactId = null;
	}
	
	if (typeof orderItemId == 'undefined' || !orderItemId)
	{
		orderItemId = null;
	}

	// See if a callback has been specified, if so save a reference

	window.__CallbackAddressEditor = null;
	
	fn = jCake.getFunctionAsCallback(fn, 'id, data');
	
	if (fn != null && typeof fn == 'function')
	{
		window.__CallbackAddressEditor = fn;
	}

	// Get address id
	var id = jQuery(".AddressId", self).val();

	// Load editor in a popup
	jQuery().jPopup({
		title: 'Edit Address'
		, url: '/addresses/edit/none/' + (id != '' ? id : '0') + (typeId != null ? '/' + typeId : '/0')+ (orderItemId != null ? '/' + orderItemId : '') +
			'?dummy' +
			(container != null ? '&container=' + encodeURIComponent(container) : '') +
			(multiLine ? '&multi_line=1' : '') +
			(contactId != null ? '&contact_id=' + contactId : '')
		, width: 530
		, height: 250
		, id: 'address-popup'
	});
}

function updateAddress(results, container)
{
	// If specified, dispatch callback
	if (parent.window.__CallbackAddressEditor != null)
	{
		parent.window.__CallbackAddressEditor(results.data.id, results.data);
		parent.window.__CallbackAddressEditor = null;
	}

	if (typeof container != 'undefined')
	{
		parent.jQuery(container).html(results.data.Address.result)
	}
	else
	{
		// Get several references
		parent.window.jQuery('input.address:hidden').each(function(obj) {
			if (obj.value == results.data.id)
			{
				jQuery('span.address', this.parentNode).html(results.data.Address.result);
			}
		});
	}

	// Close popup
	setTimeout(function() {
		parent.window.jQuery('#address-popup').jPopup('close');
	}, 50);
}

// Function used to edit an email address in a popup
function editEmailAddress(self, fn, container, typeId, inline, contactId)
{
	if (typeof container == 'undefined' || !container)
	{
		container = null;
	}

	if (typeof typeId == 'undefined' || !typeId)
	{
		typeId = null;
	}

	if (typeof inline == 'undefined' || !inline)
	{
		inline = false;
	}

	if (typeof contactId == 'undefined' || !contactId)
	{
		contactId = null;
	}

	// See if a callback has been specified, if so save a reference

	window.__CallbackEmailAddressEditor = null;

	if (fn != null && typeof fn == 'string')
	{
		fn = jCake.getFunctionAsCallback(fn, 'id, data');
	}

	if (fn != null && typeof fn == 'function')
	{
		window.__CallbackEmailAddressEditor = fn;
	}

	// Get parent record id
	var id = jQuery(".EmailAddressId", self).val();

	if (id == '')
	{
		id = 0;
	}

	var url = null;

	if (inline)
	{
		url = '/email_addresses/inline/' + id + '/0' + (contactId != null ? '/' + contactId : '')
			'?dummy' +
			(container != null ? '&container=' + encodeURIComponent(container) : '');
	}
	else
	{
		url = '/email_addresses/edit/' + id + (typeId != null ? '/0/' + typeId : '') +
			'?dummy' +
			(container != null ? '&container=' + encodeURIComponent(container) : '');
	}

	// Load editor in a popup
	jQuery().jPopup({
		title: 'Edit Email Address'
		, url: url
		, width: 530
		, height: 250
		, id: 'email-address-popup'
	});
}

function updateEmailAddress(results, container)
{
	// If specified, dispatch callback
	if (parent.window.__CallbackEmailAddressEditor != null)
	{
		parent.window.__CallbackEmailAddressEditor(results.data.EmailAddress.id, results.data.EmailAddress.data);
		parent.window.__CallbackEmailAddressEditor = null;
	}

	if (typeof container != 'undefined')
	{
		parent.jQuery(container).html(results.data.EmailAddress.result)
	}
	else
	{
		// Get several references
		parent.window.jQuery('input.email_address:hidden').each(function(obj) {
			if (obj.value == results.data.id)
			{
				jQuery('span.email_address', this.parentNode).html(results.data.EmailAddress.result);
			}
		});
	}

	// Close popup
	setTimeout(function() {
		parent.window.jQuery('#email-address-popup').jPopup('close');
	}, 50);
}

// Function used to edit a phone number in a popup
function editPhoneNumber(self, fn, container, typeId)
{
	if (typeof container == 'undefined' || !container)
	{
		container = null;
	}

	if (typeof typeId == 'undefined' || !typeId)
	{
		typeId = null;
	}

	// See if a callback has been specified, if so save a reference

	window.__CallbackPhoneNumberEditor = null;

	if (fn != null && typeof fn == 'string')
	{
		fn = jCake.getFunctionAsCallback(fn, 'id, data');
	}

	if (fn != null && typeof fn == 'function')
	{
		window.__CallbackPhoneNumberEditor = fn;
	}

	// Get parent record id
	var id = jQuery(".PhoneNumberId", self).val();

	// Load editor in a popup
	jQuery().jPopup({
		title: 'Edit Phone Number'
		, url: '/phone_numbers/edit/' + id + (typeId != null ? '/0/' + typeId : '') +
			'?dummy' +
			(container != null ? '&container=' + encodeURIComponent(container) : '')
		, width: 530
		, height: 250
		, id: 'phone-number-popup'
	});
}

function updatePhoneNumber(results, container)
{
	// If specified, dispatch callback
	if (parent.window.__CallbackPhoneNumberEditor != null)
	{
		parent.window.__CallbackPhoneNumberEditor(results.data.PhoneNumber.id, results.data.PhoneNumber.data);
		parent.window.__CallbackPhoneNumberEditor = null;
	}

	if (typeof container != 'undefined')
	{
		parent.jQuery(container).html(results.data.PhoneNumber.result)
	}
	else
	{
		// Get several references
		parent.window.jQuery('input.phone_number:hidden').each(function(obj) {
			if (obj.value == results.data.id)
			{
				jQuery('span.phone_number', this.parentNode).html(results.data.PhoneNumber.result);
			}
		});
	}

	// Close popup
	setTimeout(function() {
		parent.window.jQuery('#phone-number-popup').jPopup('close');
	}, 50);
}

// Function used to redirect user to mediasource page
// after changing status/keyword drop-down
function redirectFromMediasource(page, status, keyword)
{
	// If month and year are selected
	if (0 <= status.selectedIndex && 0 <= keyword.selectedIndex)
	{
		var url = page + status.options[status.selectedIndex].value
				+ "/" + keyword.options[keyword.selectedIndex].value;

		NemoAjaxGridsElement.load('mediasources', url);
	}
}


// Void a shipmenet
function void_shipment(orderId, shipmentId) {
	if (confirm('Are you sure you want to void this shipment?')) {
		jCake.setCursor('wait');
		jQuery.getJSON
		(
			jCake.url('/shipments/void/' + shipmentId)
			, {}
			, function(response) {
				jCake.setCursor(false);
				if (handleValidationErrors(response.data)) {
					NemoAjaxGridsElement.reload('order_shipments-'+orderId);
					NemoAjaxGridsElement.reload('order_order_items-'+orderId);
					NemoAjaxGridsElement.reload('shipping_manifest');
					NemoAjaxGridsElement.reload('shipments');
					reload_order_status();
				}
			}
		);
	}
	return false;
}


function init_tiny_mce( elements )
{
	var txt_style1 = 'bold,italic,underline';
	var separator = 'separator';
	var txt_style2 = 'strikethrough';

	//Setting alignments
	var aligns = 'justifyleft,justifycenter,justifyright, justifyfull';
	var lists = 'bullist,numlist';
	var edit_btn = 'undo,redo,link,unlink';

	//Collecting all the settings done.
	var adv_btn1 = txt_style1 + ',' + separator + ',' + txt_style2 + ',' + aligns + ',' + lists + ',' + edit_btn;

	var options =
	{
		mode: "exact"
		, elements: elements
		, theme: "advanced"
		, theme_advanced_buttons1: adv_btn1
		, theme_advanced_buttons2: ""
		, theme_advanced_buttons3: ""
		, theme_advanced_toolbar_location: "top"
		, theme_advanced_toolbar_align: "left"
	};

	tinyMCE.init( options );
}

/**
 * Add an opportunity for a custom order then take you to that page.
 */
function add_custom_order_for_entity(entityId)
{
	jCake.setCursor('wait');
	jQuery.get
	(
		jCake.url('/opportunities/add_custom_order/' + entityId)
		, {}
		, function( json )
		{
			var response = jCake.evalJson(json);
			if ( handleValidationErrors(response) )
			{
				window.location = jCake.url('/sales/dashboard/' + response.data.opportunity_id);
			}
			jCake.setCursor(false);
		}
	);

	return false;
}

function openPopup(popurl, width, height){
    w = 800;
    h = 400;
    if(typeof(width) == 'number' && width > 0){
        w = width;
    }
    if(typeof(height) == 'number' && height > 0){
        h = height;
    }
    var winpops=window.open(popurl,"","width="+ w +",height="+ h +",location,status,scrollbars,resizable");
	return winpops;
}

/**
 * jQuery plugin to check, uncheck, or toggle matching checkboxes
 */
jQuery.fn.check = function(mode) {
	var mode = mode || 'on'; // if mode is undefined, use 'on' as default
	return this.each(function() {
		switch(mode) {
			case 'on':
				this.checked = true;
				break;
			case 'off':
				this.checked = false;
				break;
			case 'toggle':
				this.checked = !this.checked;
				break;
		}
	});
};


webmail = new Object;
webmail.isValidEmail = function(){
	isValid = false;
	jQuery.ajax({
		type: "GET"
		, url: '/webmail/valid_email'
		, dataType: 'json'
		, success: function(result){
			if(result){
				jQuery('#webmail').html('<span id="newWebmail"></span> <a href="/webmail/login" target="_blank">[Login to webmail]</a> ');
				webmail.checkEmail();
				setInterval('webmail.checkEmail()', 900000);
			}
			isValid =  result;
		}
	});
	return isValid;
}

webmail.checkEmail = function(){
	jQuery.ajax({
		type: "GET"
		, url: '/webmail/check_mail'
		, dataType: 'json'
		, success: function(result){
			if(result){
				newEmail = parseInt(result.NewMessages);
				if(newEmail > 0){
					jQuery('#newWebmail').html(' <strong>You have ' + newEmail + ' new email' + (newEmail > 1 ? 's' : '' ) + '.</strong>');
				} else {
					jQuery('#newWebmail').html('');
				}
			}
		}
	});
}


