jQuery(function() {

	// If the user agent is Safari, handle the ability to click on labels to
	// set checkboxes.
	if (navigator.userAgent.indexOf("Safari") > 0)
	{
	    var labels = jQuery( 'label' );
	    for( i = 0; i < labels.length; i++ )
	    {
	        jQuery( labels[i] ).live( 'click', function() {
	            jQuery( 'input[type=checkbox] #' + this.getAttribute( 'for' ) ).each( function() {
	                this.checked = ! this.checked;
	            })
	        });
	    }
	}
	
	// See if there's any fields that need to have the validation-failed class
	// added to them.
	if( jQuery( 'input, select, textarea' ).length > 0 )
	{
		jQuery.post( '/api/status/invalidfields?format=json', function( response ) {
			var foundFields = [];

			for( var selector in response )
			{
				if( jQuery( selector ).length > 0 )
				{
					foundFields.push( selector );
					jQuery( selector ).addClass( 'validation-failed' );
				}
			}
		
			if( foundFields.length > 0 )
			{
				// Pop up the validation messages
				tb_show( 'Validation Errors', '/api/status/invalidfields?showonly=' + escape( foundFields.join( '|' ) ) + '&clearfields=true&width=450&height=250&TB_iframe=true&modal=true' );
			}
		});
	}
});

/**
* outerHTML
* Source: http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html
* Usage: jQuery( '#element' ).outerHTML
**/
(function($) {
  $.fn.outerHTML = function() {
    return $(this).clone().wrap('<div></div>').parent().html();
  }
})(jQuery);

function updateRegionControl( controlName, countryId )
{
	// Ask the server for a list 
	jQuery.get(
		'/api/address/getRegionHtml',
		{
			controlName: controlName,
			countryId: countryId
		}, function( response ) {
		
			var container = jQuery( '#' + controlName ).get( 0 ).parentNode;
			jQuery( container ).html( response );
		}
	);
}


function disableLinks()
{
	var links = document.getElementsByTagName('A');
	for (var c=0; c<links.length; c++)
	{
		links[c].href='#';
		links[c].onclick = function() { window.setTimeout('alert(\'Links are disabled in preview mode.  Close this tab or window to return to the theme selection screen.\');',10); return false; }
	}
}

function validateEmail(elem,params)
{
	if (params.onCheck)	params.onCheck(elem);
	new Ajax.Request('/admin/rpc/action.php?asset=validate&action=email',
	{
		method: 'post',
		parameters: {
			input: elem.value
		},
		onSuccess: function(trans) {
			params.onSucecss(elem);
		},
		onFailure: function(trans) {
			params.onFailure(elem);
		}
	});
}

function showErrorMessage(message)
{
	window.setTimeout(function(){ alert(message); },50);
}

function ajaxMessage(message,timeout)
{
	jQuery( 'body' ).append( '<div class="ajax-message"><span>' + message + '</span></div>' );
	window.setTimeout( function() {
		jQuery( '.ajax-message' ).fadeOut(
			'fast',
			function(){
				jQuery( this ).remove();
			}
		)
	}, timeout );
}



