function tabsTriggers(jqtarget){
    $(jqtarget).bind('tabsadd', function(d){ tabsadd(d) });
    $(jqtarget).bind('tabsshow', function(d){ tabsshow(d) });
    $(jqtarget).bind('tabsremove', function(d) { tabsremove(d) });
    $(jqtarget).bind('tabsenable', function(d) { tabsenable(d) });
    $(jqtarget).bind('tabsdisable', function(d) { tabsdisable(d) });
    $(jqtarget).bind('tabsload', function(d) { tabsload(d) });
    $(jqtarget).bind('tabsselect', function(d) { tabsselect(d) });
}

function tabsDriver(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex){
	
	/* Pattern Match, run first as the the rest below may attach to modified HTML */
	//runPatterns(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
	
    /* Links */
    createCloseLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    createNewLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    createCurrentLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    
    createPopupLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    
    /* Forms */
    createCurrentForms(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    createSaveAndCloseButtons(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    createSaveButtons(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    
    if(ATTACHCROP){attachCrop($(tabsElemExp)); }
    
    /* Date Pickers */
    jQuery.datepick.initDatePickers();
    nicEdit.run(tabsElemExp);
}

var nicEdit = {
    count : 0,
    editors : new Array(),
    run : function(tabsElemExp){
        $(tabsElemExp + ' .nicEdit').each(function(){
            if(!$(this).attr('id')){
                $(this).attr('id', 'nicEdit_'+nicEdit.count)   
            }
            if($(this).attr('initialized') != 'true'){
                nicEdit.editors.push(new nicEditor({iconsPath : '/js/nicEditorIcons.gif', buttonList : ['bold','italic','underline','link','left','center','right','justify','ol','ul','strikethrough','indent','outdent','hr']}));
                var last = nicEdit.editors.length - 1;
                nicEdit.editors[last].panelInstance($(this).attr('id'));
                $(this).attr('initialized', 'true')
            }        
            
        });
    },
    
    save : function(tabsElemExp){
        $(tabsElemExp + ' .nicEdit').each(function(){
            var editor = nicEditors.findEditor($(this).attr('id'));
            editor.saveContent();
        });
    }
};

function tabsadd(d){
    //alert('tabsadd');
}

function tabsshow(d){
    //alert(d['target']['parentNode']['id']);
    
    var tabsContainerId = d['target']['parentNode']['id'];
    var tabsContainerElemExp = "#" + tabsContainerId + " > ul";
    var tabsSelectedIndex = $(tabsContainerElemExp).data('selected.tabs');
    var tabsId = '';

    var t = $('#' + tabsContainerId)[0]['childNodes'];
    var i = 0;
    
    for(var item in t){
        if(t[item].nodeName == 'DIV'){

            if(i == tabsSelectedIndex){
                tabsId = t[item]['id'];
                break;
            }
            i++;
        }
    }
    
    var tabsElemExp = "#" + tabsId;
    
    tabsDriver(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
    $('.ui-tabs-hide').each(function(){
        $(this).attr('style', 'display: none');
    });
}

function tabsremove(d){
    //alert('tabsremove');   
}

function tabsenable(d){
    //alert('tabsenable');   
}

function tabsdisable(d){
    //alert('tabsdisable');   
}

function tabsload(d){    
    //alert('tabsload');
}

function tabsselect(d){
    greyout();
    //alert('tabsselect');
	$('.context_menu').remove();
	$('.context-menu-shadow').remove();
}

function greyout(){
    $('.ui-tabs-panel:visible').each(function(){
        $(this).wrapInner('<div class="tabs-grey-out"></div>');
        $(this).append('<div class="tabs-loading"><p>' + LOADING + '...</p><img src="/img/tabs-ajax-loader.gif" /></div>');
    });
}

/* Links */
function createCloseLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex){
    $(tabsElemExp + ' a.tabsClose, ' + tabsElemExp + ' input.tabsClose').click( function(){ $(tabsContainerElemExp).tabs('remove', tabsSelectedIndex); } );
}

function createNewLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex){
    $(tabsElemExp + ' a.tabsNew, ' + tabsElemExp + ' input.tabsNew').click(
        function(){
            if($(this).attr('href').indexOf('?') == -1){
                var href = $(this).attr('href') + '?ajax';
            }
            else{
                var href = $(this).attr('href') + '&ajax';
            }
            $(tabsContainerElemExp).tabs( 'add', href, $(this).attr('title') );
            $(tabsContainerElemExp).tabs( 'select', $(tabsContainerElemExp).tabs('length') - 1);
            
            window.location.hash = '#home';
            return false;
        }
    );
}

function createCurrentLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex){
    $(tabsElemExp + ' a.tabsCurrent, ' + tabsElemExp + ' input.tabsCurrent').click(
        function(){
            greyout();
            if($(this).attr('href').indexOf('?') == -1){
                var href = $(this).attr('href') + '?ajax';
            }
            else{
                var href = $(this).attr('href') + '&ajax';
            }
            $(tabsContainerElemExp).tabs( 'url', tabsSelectedIndex, href);
            $(tabsElemExp).load(href, null, function(){ tabsDriver(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex); } );
            
            window.location.hash = '#home';
            return false;
        }
    );
}

function createPopupLinks(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex)
{
    $(tabsElemExp + ' a.popup, ' + tabsElemExp + ' input.popup' ).each(function (i){
        $(this).click(function(event) {
            event.preventDefault();
            var params = $(this).data("popup") || {};            
            if ($(this).attr("target"))
            {
                params.windowName = $(this).attr("target");
            }
            var windowObject = UTIL.popup.open($(this).attr('href'), params);
            $(this).data("windowObject", windowObject);
        });
    });

}
/* Forms */

function createCurrentForms(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex){
    $(tabsElemExp + ' form.tabsCurrent').each( function(){ this.onsubmit = function(){
            greyout();
            nicEdit.save(tabsElemExp);
            if($(this).attr('action').indexOf('?') == -1){
                var href = $(this).attr('action') + '?ajax';
            }
            else{
                var href = $(this).attr('action') + '&ajax';
            }
            
            //tinyMCE.triggerSave();
            
            /* only supports posts right now */
            $.post(
                href, 
                $(this).serializeArray(),
                function(data){
                    $(tabsElemExp).html(data);
                    $(tabsContainerElemExp).tabs( 'url', tabsSelectedIndex, href);
                    tabsDriver(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
                },
                'html'
            );
            
            window.location.hash = '#home';
            return false;
    }});
}

function createSaveAndCloseButtons(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex){
    $(tabsElemExp + ' input.tabsSaveAndClose').each(function(){ this.onclick = function(){
        $(tabsElemExp + ' form.tabsSaveAndClose').each(function(){
			greyout();
			nicEdit.save(tabsElemExp);
			if($(this).attr('action').indexOf('?') == -1){
				var href = $(this).attr('action') + '?ajax';
			}
			else{
				var href = $(this).attr('action') + '&ajax';
			}
			
			$.post(
				href, 
				$(this).serializeArray(),
				function(data){ $(tabsContainerElemExp).tabs('remove', tabsSelectedIndex); }, 
				'html'
			);
			
		});
    }});
}

function createSaveButtons(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex){
    $(tabsElemExp + ' input.tabsSave').each(function(){ this.onclick = function(){
        $(tabsElemExp + ' form.tabsSave').each(function(){
			greyout();
			nicEdit.save(tabsElemExp);
			if($(this).attr('action').indexOf('?') == -1){
				var href = $(this).attr('action') + '?ajax';
			}
			else{
				var href = $(this).attr('action') + '&ajax';
			}
			
			//tinyMCE.triggerSave();
			
			$.post(
				href, 
				$(this).serializeArray(),
				function(data){
					$(tabsElemExp).html(data);
					$(tabsContainerElemExp).tabs( 'url', tabsSelectedIndex, href);
					tabsDriver(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex);
				},
				'html'
			);  
        });
    }});
}

function runPatterns(tabsContainerElemExp, tabsElemExp, tabsSelectedIndex)
{
	/* Locate Emails for MailChimp Context Menu */
	/*
	$(tabsElemExp).patternWrap(
		$.patterns.email, 
		{
			tagName : 'span', 
			class : 'mailchimp_context_menu'
		}
	);
	*/	
}