//Setup a PlanetTagger namespace
var PT = PT || {};

//Setup the event
PT.frontpage = function( e, options ){
	
	//show the user that this target is loading
	SDNA.loading(options.target);
	
	var $action = $j(options.target);
	
	if( $action.is('[href*=.htm]') ){ // this link is an ajax request	
		Window.pop( 
			options.url, 
			{
				close: function(){
					SDNA.loaded(options.target);
				}
			} 
		);
		
	}
};

PT.frontpage.click = function( e ){	              
	//keep this link from functioning
	e.preventDefault();
	
	SDNA.Event.trigger(
		'edit_fp',  
		{ 
			url: $j(this).attr('href'), 
			target: this 
		}
	);
};

// bind front page, @see pt.init.js
PT.frontpage.bind = function(){
	$j('a.edit_fp').live('click.edit_fp', PT.frontpage.click);
};

PT.frontpage.submitted = function(){
	window.location.reload();
};

PT.frontpage.closeWindow = function(){
    if( Window ){
        Window.close();
    }   
}

PT.frontpage.bindEditor = function(){
    $j('#edit_fp_view form textarea[name=content]').eq(0).wysiwyg({width: '390', height: '270'});
    SDNA.Event.unsubscribe('window.shown', PT.frontpage.bindEditor);
};

PT.frontpage.bindEditor.bound = false;

PT.frontpage.bindWindow = function( $dom ){
    //make sure this html is a jquery obj
    $html = $j($dom);
    // setup Cancel button to close the popup window
    $html.find('form button[name=cancel]')
        .unbind('click.cancel')
        .bind('click.cancel', PT.frontpage.closeWindow);
    
    
    $html.find('form').unbind('submit.frontpage').bind('submit.frontpage',
        function(e) { 
            e.preventDefault();
            $this = $j(this);
    
            //save the settings
            $j.post(
                $this.attr('action'),
                $this.serialize(),
                function( response ){                   
                    if( response.success == true ){                     
                        //now close this modal
                        $this.trigger('submitted');
                        SDNA.Event.publish('frontpage.submitted',{});
                        PT.frontpage.closeWindow();                     
                    }                   
                },
                'json'
            );
        }
    );
    
    if (!PT.frontpage.bindEditor.bound) {
        // set up subscription to window.shown event to bind the wysiwyg editor
        // @see sdna.window.js where this event is published whenever a popup is shown
        SDNA.Event.subscribe('window.shown', PT.frontpage.bindEditor );
        
        PT.frontpage.bindEditor.bound = true;
    }
};

 