AviaryChannel = {
    activeDoc: 0,
    
	docs : [
    {	id: null,
	    title: null,	
	    url: null,
	    currentState: 'unsaved',
	    datetime: null,
	    savebarOriginalState: 'unsaved',
	    savebarHtml: null,
	    tags: null,
	    description: null,
	    license: null,
	    permissions:null
	}
	] 
	
    ,
	bgsave: false,

	
	init: function( id )
	{
		this.docs[this.activeDoc].id = id.toLowerCase();
		
		var el = document.getElementById( 'saveas-aviary-title' );
		
		if( el )
		{
			this.docs[this.activeDoc].title = el.value;
		}
		
		var scope = this;
		
		
		setTimeout( function(){ scope.setupSwitching(); }, 1000 );
	},
	
	addDoc: function ( id, state, title, url, saveddatetime )
	{
	    var doc = {};
	    doc.id = id.toLowerCase(); 
	    doc.title = title;
	    doc.url = url;
	    doc.currentState = state;
	    doc.datetime = saveddatetime;
	    
	    this.docs.push(doc);

	    return (this.docs.length -1 );	
	},
	
	activateDoc: function ( idx ) 
	{
	    var oldIdx = this.activeDoc;
	    this.docs[oldIdx].description = $('#saveas-aviary-description').val();
	    this.docs[oldIdx].tags = $('#saveas-aviary-tags').val();
	    this.docs[oldIdx].license = $('#licenseForm input').serialize() ;
	    this.docs[oldIdx].permissions = $('#permissionsForm input').serialize()
	    
	    this.activeDoc = idx;
	    
	   	if(this.docs[idx].currentState == 'saved') {
	        $.AviarySaveBar.setState( 'saved', {title: this.docs[idx].title, url: this.docs[idx].url, datetime: this.docs[idx].datetime });
	    } else {
	        $.AviarySaveBar.setState( 'unsaved', {});
	        if (this.docs[idx].title != null && this.docs[idx].title != "" && this.docs[idx].title != "Untitled") {
	            $('#savebar-title').text(this.docs[idx].title);
	        }
	    }
        $('#saveas-aviary-title').val(this.docs[idx].title.replace('.egg', '').replace('.jpg', '').replace('.gif', '').replace('.png', ''));
        $('#saveas-aviary-description').val(this.docs[idx].description);
        $('#saveas-aviary-tags').val(this.docs[idx].tags);
	},
	
	setupSwitching: function()
	{
		var scope = this;
		
		window.onfocus = function()
		{
			scope.sendMessage( "activated", {} );
		};
		
	},
	
	openChildApplication: function( app_id, cookie )
	{
		var tid;
		var appname;
		
		switch( app_id )
		{
			case 'phoenix': tid = 1; appname = 'Phoenix'; break;
			case 'peacock': tid = 3; appname = 'Peacock'; break;
			case 'raven': 	tid = 4; appname = 'Raven'; break;
			case 'toucan': 	tid = 2; appname = 'Toucan'; break;
			case 'myna': 	tid = 6; appname = 'Myna'; break;
			case 'roc': 	tid = 7; appname = 'Roc'; break;
			
			default:
				return false;
		}
		
		return window.open( "index.aspx?tid=" + tid + "&" + appname + "&switching=" + cookie, cookie, 'height=750,width=1000,fullscreen=yes, menubar=no, location=no, toolbar=no, resizable=yes' ) ? true : false;
	},
	
	onAviaryReady: function()
	{
		
	},
	
	onApplicationReady: function()
	{	
		var scope = this;
	
		setTimeout( function()
		{
			if( !scope.gup( 'switching' ) )
			{
				var action = prompt( "What do u want to do (1 - new, 2 - open, 3 - import)?", "1" );
				
				switch( action )
				{
					case "1":
						scope.sendMessage( "new", {} );
						break;
					
					case "2":
						var egg = prompt( "EGG", "http://testrookery.viary.com/storagev12/500500/500996_6004.egg" );
						var title = prompt( "Title", "test+new.egg" );
						var force = prompt( "Force", "false" );
						// var fileversionguid = 'c3b8847a-5a36-102c-b57e-405c0d2db816';
						
						scope.sendMessage( 'open', { egg: egg, title: title, force: force, type: "egg" } );
						break;
					
					case "3":
						var egg = prompt( "EGG", "http://testrookery.viary.com/storagev12/500500/500902_a319.egg" );
						var title = prompt( "Title", "xscdfvbk%2c..egg" );
						var source = prompt( "Source", "1" );
						var fileversionguid = prompt( "fileversionguid", "8d3577f7-5938-102c-b57e-405c0d2db816" );
						
						scope.sendMessage( 'import', { egg: egg, title: title, force: "false", type: "egg", source: source, fileversionguid: fileversionguid } );
						break;
				}
			}
		}, 1000 );
	},
	
	enableSave: function()
	{
		
	},
	
	disableSave: function()
	{
		
	},
	
	getCookie: function()
	{
		return this.gup( 'switching' );
	},
	
	gup: function( name )
	{
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );

		if( results == null )
		{
			return null;
		}else
		{
			return results[ 1 ];
		}
	},
	
	sendMessage: function( msg, param )
	{
	param = param || {};
		
		var app = document.getElementById( this.docs[this.activeDoc].id.toLowerCase() );
		
		if( app != null && app.sendMessage)
		{
			return app.sendMessage( msg, param );
		}
		
		return false;
	},
	
	save: function()
	{
		this.bgsave = true;
		
		this.sendMessage( 'do_save', {} );
	},
	
	commit: function()
	{
		this.sendMessage( 'do_commit', {} );
	},
	
    
	saveAs: function( settings )
	{
		/*
		operation: new,overwrite
		select-permission-view: everyone,contacts,restricted,private
		select-permission-edit: everyone,contacts,restricted,private
		chooseLicense-default: true
		saveas-aviary-permissions-defaults: defaults
		chooseLicense: copyright,cc-by,cc-by-nc
		saveas-aviary-description: 
		saveas-aviary-tags: 
		saveas-aviary-title: 
		*/
	 
		
		this.docs[this.activeDoc].title = settings[ 'saveas-aviary-title' ];
		this.bgsave = false;

		this.sendMessage( 'do_save_as', {
			title: settings[ 'saveas-aviary-title' ],
			description: settings[ 'saveas-aviary-description' ],
			tags: settings[ 'saveas-aviary-tags' ],
			settings: settings
		} );
		
				
	},
	
	onSaveProgress: function( value )
	{
	   if( this.bgsave )
			$.AviarySaveBar.setState('saving', {percent: value});
		else
			$.AviaryDialogs.setProgress('#appdialogs-overlay-progress', value);

	},
	
	onSaveComplete: function( url )
	{
		var title = Encoder.htmlDecode( this.docs[this.activeDoc].title );
		var currentDate =  this.getCurrentDate();
		
		this.docs[this.activeDoc].url = url;
		this.docs[this.activeDoc].currentState = 'saved';
		this.docs[this.activeDoc].datetime = currentDate;

		
		if( this.bgsave )
		{
			$.AviarySaveBar.setState( 'saved', {title: title, url: url, datetime: currentDate });
		}else
		{
			$.AviaryDialogs.setProgress('#appdialogs-overlay-progress', 100, function()
			{
				$.AviaryDialogs.overlayOff();
				$.AviaryDialogs.activate( 'savebar' );
				$.AviarySaveBar.setState( 'saved', {title: title, url: url, datetime: currentDate});
		    });
		}
	},
	
	onSaveError: function( msg )
	{
			   
		alert( msg );
		 
	    $.AviaryDialogs.overlayOff();
		$.AviaryDialogs.activate( 'savebar' );
		
		if( !this.gup( 'switching' ) )
		{
	        if (this.docs[this.activeDoc].savebarOriginalState == 'saved') {
	        
    		    $('#savebar').replaceWith(this.savebarHtml);
    		}
    		else 
    		{
    		    $.AviarySaveBar.setState( 'unsaved', {})
    		}	   
		}
		else
		{
		    $.AviarySaveBar.setState( 'unsavedswitching', {} );
		}
		
	},
	
	onNewDocument: function()
	{
		if( !this.gup( 'switching' ) )
		{
			$.AviarySaveBar.setState( 'unsaved', {});
		}else
		{
			$.AviarySaveBar.setState( 'unsavedswitching', {} );
		}
					
		this.docs[this.activeDoc].currentState = 'unsaved';
	},
	
	getCurrentDate: function()
	{
	    var now = new Date();
	    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	    var hours = now.getHours() == 0 ? 12 : (now.getHours() > 12 ? now.getHours() % 12 : now.getHours());

	    var min = now.getMinutes();
	    if (min < 10) { min = '0' + min }

	    var ampm = now.getHours() >= 12 ? 'PM' : 'AM';

	    return (months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear() + ' at ' + hours + ':' + min + ampm);
	}
};



