    var _ErrorMessage = "JavascriptError: \n\tFile:\n\t\t{0} \n\tFunction:\n\t\t{1} \n\tError Message:\n\t\t {2}";

    /// <summary>
    /// Throw the exception formated for the user
    /// </summary>
    function ShowException(file,fcn,msg)
    {
        alert(_ErrorMessage.toString().replace('{0}',file).replace('{1}',fcn).replace('{2}',msg));
    }
    
    /// <summary>p
    /// Adjust the page layout, called every request
    /// </summary>
    function AdjustLayout()
    {
        try
        {
            AdjustInputFocus();
            AdjustToolTip();
            AdjustInputType();
            AdjustConfirmButton();
            Atria_SwapLink();
            EnableInLineEdit();
        }
        catch(ex)
        {
            ShowException('Atria.Base.js','AdjustLayout();',ex.message);
        }
    }
    
    /// <summary>
    /// Logout the user
    /// </summary>
    function ApiBminds_Atria_LogoutUser()
    {
        $.getScript('/Services/User/Logout.aspx');
    }

    /// <summary>
    /// Adjust the tool tip plugin
    /// </summary>
    function AdjustToolTip()
    {
        try
        {
			$('.ui-dropdown').selectmenu({style:'dropdown'});
			$('[title]:not(.hidetitle)').tooltip({
				fade: false,
				showURL: false,
				track: true
			});
        }
        catch(ex)
        {
        }
    }
    
    /// <summary>
    /// Enable In Line Edit
    /// </summary>
    function EnableInLineEdit()
    {
        try
        {
            $('.Atria_InlineEdit').click(function(){
            
                var label = $(this);
                var textbox = label.next();
                var control = textbox.next();
                
                label.hide();
                textbox.show().focus();
                
                textbox.unbind('blur');
                textbox.bind('blur', function(){
                    if (textbox.val() != label.text().trim() && textbox.val() != "")
                    {
                         $.prompt(control.text().replace('%new',textbox.val()).replace('%old',label.text().trim()),{
                              prefix:'Atria_Global_Warning',   
                              callback: function(v,m) { if (v == true) { control.click(); label.show().next().hide().next().hide(); } else { textbox.val(label.text().trim()); label.show().next().hide(); } return true; },
                              buttons: { Ok: true, Cancel: false }
                        });
						$('.Atria_Global_Warningfade').addClass('ui-widget-overlay');
						$('.Atria_Global_Warningcontainer').addClass('ui-widget-content').addClass('ui-corner-all');
						$('.Atria_Global_Warningbuttons>button').addClass('ui-state-default').addClass('ui-button');
                    } else {
                        label.show().next().hide();
                        textbox.val(label.text().trim());
                    }
                });
            });
            
            $('.Atria_InlineEditCombo').click(function(){
                var label = $(this);
                var combo = label.next();
                var control = combo.next();
                
                label.hide();
                combo.show().focus();
                
                combo.unbind('blur');
                combo.bind('blur', function(){
                    var comboText = $('option[selected=selected]',combo).text();
                    if (combo.val() != label.attr('rel').trim() && combo.val() != "")
                    {
                         $.prompt(control.text().replace('%new',comboText).replace('%old',label.text().trim()),
                         {
                            prefix:'Atria_Global_Warning',   
                            callback: function(v,m) { if (v == true) { control.click(); label.show().next().hide().next().hide(); } else { combo.val(label.text().trim()); label.show().next().hide(); } return true; },
                            buttons: { 
                                Ok: true, 
                                Cancel: false
                            }
                        });
						$('.Atria_Global_Warningfade').addClass('ui-widget-overlay');
						$('.Atria_Global_Warningcontainer').addClass('ui-widget-content').addClass('ui-corner-all');
						$('.Atria_Global_Warningbuttons>button').addClass('ui-state-default').addClass('ui-button');
                    } else {
                        label.show().next().hide();
                        combo.val(label.text().trim());
                    }
                });
            });
        }
        catch(ex)
        {
            ShowException('Atria.Base.js', 'EnableInLineEdit();', ex.message);
        }
    }
    /// <summary>
    /// Puts the href link in a onclick function
    /// </summary>
    function Atria_SwapLink()
    {
        try
        {
            //bind the click function with the oldhref attr value
            $('.Atria_SwapLink').bind('click', function(){
                eval($(this).attr('oldhref'));
            });
            
            //remove href and puts in the oldhref
            $('.Atria_SwapLink').each(function(){
                $(this).attr('oldhref',$(this).attr('href').substring(11));
            });
                
            //clear href
            $('.Atria_SwapLink').attr('href','#');
        }
        catch(ex)
        {
        }
    }


        /// <summary>
    /// Display a confirm message in all delete buttons
    /// </summary>
    function AdjustConfirmButton()
    {
        try
        {
            //bind the click function with the oldhref attr value
            $('.ConfirmButton').bind('click', function(){
            
                var button = $(this);
                var text = button.attr('ConfirmText') == undefined ? 'Confirm delete?' : button.attr('ConfirmText');
                var ok = button.attr('ConfirmTextOk') == undefined ? 'Yes' : button.attr('ConfirmTextOk');
                var cancel = button.attr('ConfirmTextCancel') == undefined ? 'No' : button.attr('ConfirmTextCancel');
               
                $.prompt(
                    text,
                    { 
                        buttons: { Ok: ok, Cancel: cancel }, 
                        zIndex: 99999999,
                        focus: 1, 
                            prefix:'Atria_Global_Warning',   
                        callback : function(v,m) { 
                            if (v == ok) { 
                                eval(button.attr('oldhref').substring(11)); 
                            } 
                        }
                    }
                );
				$('.Atria_Global_Warningfade').addClass('ui-widget-overlay');
				$('.Atria_Global_Warningcontainer').addClass('ui-widget-content').addClass('ui-corner-all');
				$('.Atria_Global_Warningbuttons>button').addClass('ui-state-default').addClass('ui-button');
            });
            
            //remove href and puts in the oldhref
            $('.ConfirmButton').each(function(){
                    $(this).attr('oldhref',$(this).attr('href'));
            });
                
            //clear href
            $('.ConfirmButton').attr('href','#');

            //make confirm required
        }
        catch(ex)
        {
            ShowException('Atria.Base.js', 'AdjustConfirmButton();', ex.message);
        }
    }
 
    /// <summary>
    /// Change the inputs border on focus
    /// </summary>
    function AdjustInputFocus() 
    { 
        try
        {
			$('.Atria_CrudList_ListPortalSimple_AlternateItem, .Atria_CrudList_ListPortalSimple_Item').hover(function(){
				$(this).addClass('ui-state-hover');
			},function(){
				$(this).removeClass('ui-state-hover');
			});
            $('.ui-state-default:not(.nohover), .dohover').hover(function(){
				$(this).addClass('ui-state-hover');
			},function(){
				$(this).removeClass('ui-state-hover');
			});
			$('.dofade').hover(function(){
				$(this).fadeTo("slow", 1);
			},function(){
				$(this).fadeTo("slow", 0.3);
			});
			$('.Container_CrudList_Grid tr').hover(function(){
				if ($('th',$(this)).length == 0) {
					$(this).addClass('ui-state-hover');
				}
			},function(){
				if ($('th',$(this)).length == 0) {
					$(this).removeClass('ui-state-hover');
				}
			});
			$('body').addClass('ui-widget-content');
        }
        catch(ex)
        {
            ShowException('Atria.Base.js','AdjustInputFocus();',ex.message);
        }
    }

    /// <summary>
    /// Active JQuery Wysiwyg plugin
    /// </summary>
    function AdjustInputType()
    {
        try
        {
            //$("textarea.JQueryWysiwyg").wysiwyg();
        }
        catch(ex)
        {
            ShowException('Atria.Base.js','AdjustInputType();',ex.message);
        }
    }

    /// <summary>
    /// Gets the site Url
    /// </summary>
    /// <returns>the current base url</returns>
    function GetSiteUrl()
    {
        try
        {
            var url = window.location.href;
            var nohttp = url.split('//')[1];
            var hostPort = nohttp.split('/')[0];
                
            return 'http://' + hostPort;
        }
        catch(ex)
        {
            ShowException('Atria.Base.js','GetSiteUrl();',ex.message);
        }
    }
    
    /// <summary>
    /// Requests Variable from query string
    /// </summary>
    /// <param name="name">the var key.</param>
    /// <returns>the var value</returns>
    function RequestVar( name )
    {
        try
        {
            name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
            var regexS = "[\\?&]"+name+"=([^&#]*)";
            var regex = new RegExp( regexS );
            var results = regex.exec( window.location.href );
            
            if( results == null )
                return "";
            else
                return results[1];
        }
        catch(ex)
        {
            ShowException('Atria.Base.js','RequestVar(name:' + name + ');',ex.message);
        }
    }

    /// <summary>
    /// Makes the control draggables and droppables
    /// </summary>
	function EditArea_MakeDraggable()
	{
        try
        {
            $('div.Atria_EditArea_Content_Area_Control').draggable({
                helper: function() { 
                    return $('<div class="Atria_EditArea_Content_Area_Control" style="background-color:white; opacity: 0.8; filter: alpha(opacity=80); width: 250px; height: 100px; overflow: hidden;"></div>').append($(this).html());
                },
                handle: $('.Atria_EditArea_Content_Control_Header_Handler')
            });
            //From Trash List
            $('div.Atria_EditArea_Trash_Control').draggable({
                helper: 'clone',
                handle: $('.Atria_EditArea_Content_Control_Header_Handler')
            });
	        $('div.Atria_EditArea_Content_Area_Sortable').droppable({
		        accept: 'div.Atria_EditArea_Content_Area_Control',
		        activeClass: 'Atria_EditArea_Content_Area_Sortable_Active',
		        hoverClass: 'Atria_EditArea_Content_Area_Sortable_Hover',
		        drop: function(ev, ui) {
			        var $that = $(this);
                    // if is another sortable area
                    if (ui.draggable.parent().hasClass('Atria_EditArea_Content_Area_Sortable')) {
			            $that.append(ui.draggable);
                    } else if (ui.draggable.parent().hasClass('Atria_TrashArea_TrashControls')) {
                        //if is from the trash bucket
                        $that.append(($.cookie(ui.draggable.attr('ControlId'))));
                    } else {
                        //if is to a sortable area from the control list
                        ui.draggable.css('z-index','');
                        $that.append('<div class="Atria_EditArea_Content_Area_Control">' + ui.draggable.attr('style','').html() + '</div>');
                    }
		        }
	        });
	        $('.Atria_TrashArea_TrashControls').droppable({
                accept : '.Atria_EditArea_Content_Area_Control',
                activeclass: 'Atria_TrashArea_TrashControls_Active',
                hoverclass: 'Atria_TrashArea_TrashControls_Hover',
                drop: function(e, ui) { 
                    if (ui.draggable.parent().attr('class') != undefined && ui.draggable.parent().attr('class').indexOf('Atria_EditArea_Content_Area_Sortable') != -1) {
                        EditArea_RemoveControl(ui.draggable);
                    }
                }
            });
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','EditArea_MakeDraggable()',ex.message);
        }
	}
	
    /// <summary>
    /// Check trash box, if is empty change the picture
    /// </summary>
	function EditArea_CheckTrash(forceClear)
	{
	    try
	    {
            if (forceClear || ($('.Atria_TrashArea_TrashControls').children() == undefined || $('.Atria_TrashArea_TrashControls').children().eq(0).length == 0))
            {
	            $('.Atria_TrashArea_TrashIcon').empty();
                $('.Atria_TrashArea_TrashIcon').append('<img src="/Content/Images/Atria/trash_empty.png" border="0" />');
                $('.Atria_TrashArea_TrashControls').empty();
            }
            else
            {
	            $('.Atria_TrashArea_TrashIcon').empty();
                $('.Atria_TrashArea_TrashIcon').append('<img src="/Content/Images/Atria/trash_full.png" border="0" />');
            }
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','SelectControl_ClearTrash()',ex.message);
        }
    }

    /// <summary>
    /// Toggles Control Beside
    /// </summary>
    /// <param name="control">the control to toggle beside.</param>
	function EditArea_ToggleBeside(control)
	{
	    try
	    {
	        if (control.css('float') == 'left') {
	            control.css('float','none');
	        } else {
	            control.css('float','left');
	        }
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','EditArea_ToggleBeside(control: ' + control + ')',ex.message);
        }	
    }
    
    /// <summary>
    /// Moves the control in the area
    /// </summary>
    /// <param name="control">the control to move.</param>
    /// <param name="control">the direction (next, previous).</param>
    function EditArea_Move(control, direction)
	{
	    try
	    {
            if (direction == 'next') {
                if (control.next().html() != null) {
                    control.insertAfter(control.next());
                } else {
                    control.parent().prepend(control);
                }
            } else {
                if (control.prev().html() != null) {
                    control.insertBefore(control.prev());
                } else {
                    control.parent().append(control);
                }
            }
             
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','SelectControl_Move(control: ' + control + ', direction: ' + direction + ')',ex.message);
        }
        finally
        {
            CheckCookies();
        }
    }
    
    function EditArea_RemoveControl(control)
    {
        if ($(control).attr('ControlId') != null && $(control).attr('ControlId') != '') {
            $.cookie('Atria_TrashControls_' + $(control).attr('ControlId'),$('<div></div>').append($(control)).html());
            $('.Atria_TrashArea_TrashControls').append($('<li><div ControlId="' + $(control).attr('ControlId') + '" class="Atria_EditArea_Trash_Control">' + $('div.Atria_EditArea_Content_Control_Header > strong',control).html() + '</div></li>'));
        }
        
        $(control).remove();
        EditArea_CheckTrash(false);
    }
    
    function ToggleControlList()
    {
	    try
	    {
            if ($('div.Atria_ControlMenu_Menu').css('left') == '0px') {
                CloseControlList();
            } else {
                OpenControlList();
            }
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','ToggleControlList()',ex.message);
        }	
    }
    
    function CloseControlList()
    {
	    try
	    {
            $('.Atria_ControlMenu_Close').animate({left:0});
	        $('.Atria_ControlMenu').accordion("activate", -1);
            $('.Atria_ControlMenu').accordion('disable');

            if (!$.browser.msie) {
                $('div.Atria_ControlMenu_Menu').animate({left:-265, opacity: 1}, 'fast');
            } else {
                $('div.Atria_ControlMenu_Menu').animate({left:-265}, 'fast');
            }
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','CloseControlList()',ex.message);
        }	
    }    

    function ForceCloseControlList()
    {
	    try
	    {
            $('.Atria_ControlMenu_Close').css('left','0px');
	        $('div.Atria_ControlMenu_Menu').css('left','-265');
	        $('.Atria_ControlMenu').accordion("activate", -1);
            $('.Atria_ControlMenu').accordion('disable');
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','CloseControlList()',ex.message);
        }
    }      
    
    function OpenControlList()
    {
	    try
	    {
            $('.Atria_ControlMenu_Close').animate({left:275});
            $('.Atria_ControlMenu').accordion('enable');
	        $('.Atria_ControlMenu').accordion("activate", -1);

            if (!$.browser.msie) {
                $('div.Atria_ControlMenu_Menu').animate({left:0, opacity: 0.8}, 'fast');
            } else {
                $('div.Atria_ControlMenu_Menu').animate({left:0}, 'fast');
            }
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','OpenControlList()',ex.message);
        }
    }
    
    function CopyPageToggle(item)
    {
        try
        {
            if (item.val().toString().trim() == '') {
                if ($('.Atria_CopyPage_Tree').css('display') != 'none') {
                    $('.Atria_CopyPage_Tree').hide('slide',{ direction: 'up' },500);
                } 
            } else {
                if ($('.Atria_CopyPage_Tree').css('display') == 'none') {
                    $('.Atria_CopyPage_Tree').show('slide',{ direction: 'up' },500);
                }
            }
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','CopyPageToggle(item: ' + item + ')',ex.message);
        }
    }

    function CheckCookies()
    {
        try
        {
            //Search in sortable areas
            var withBeside = '';
            $.each($('.Atria_EditArea_Content_Area_Sortable'), function(i,area){
	            var values = '';
	            $.each($('.Atria_EditArea_Content_Area_Control', this), function(j,comp){
		            values += (j != 0 ? "," : '') + $(comp).attr('ControlId');
		            if ($(comp).css('float') == 'left') {
		                withBeside += (withBeside != '' ? "," : '') + $(comp).attr('ControlId');
		            }
	            });
	            $.cookie('EditArea_ControlsPosition_' + $(area).attr('AreaId'), values, { path: '/' });
            });
            $.cookie('EditArea_Controls_WithBeside', withBeside, { path: '/' });
            
            //Search in Trash
            var trashValues = '';
            $.each($('.Atria_EditArea_Trash_Control'), function(i, control){
		        trashValues += (i != 0 ? "," : '') + $(control).attr('ControlId');
            });
            $.cookie('EditArea_Controls_Trash', trashValues, { path: '/' });
        }
        catch(ex)
        {
		    ShowException('Atria.Base.js','CheckCookies()',ex.message);
        }
    }    
    
    function Atria_Validators_ValidateLength(src, args) {
    
        var minLength = $(src).attr('ValidateLength_Min');
        var maxLength = $(src).attr('ValidateLength_Max');
        
        if (minLength != null && maxLength != null) {
            args.IsValid = args.Value.toString().length >= minLength && args.Value.toString().length <= maxLength;
        } else if (minLength != null && maxLength == null) {
            args.IsValid = args.Value.toString().length >= minLength;
        } else if (minLength == null && maxLength != null) {
            args.IsValid = args.Value.toString().length <= maxLength;
        }
    }
    
    function CrudList_OpenSearchBox(buttonId) {
	    $('#Container_CrudList_SearchBox').dialog({
		    bgiframe: true,
		    height: 300,
		    modal: true,
		    buttons: {
			    'Cancelar': function() {
				    $(this).dialog('destroy');
			    },
			    'Buscar': function() {
				    $('#' + buttonId).click();
				    $(this).dialog('destroy');
			    }
		    },
		    close: function() {
			    $(this).dialog('destroy');
		    }
	    });
    }
