if (typeof BKLET == "undefined" || !BKLET) {
    var BKLET = {};
}

BKLET.active = false;

BKLET.key = '7f62e2a46733235403561264393830'; // Meetup API key
BKLET.yqlResult = null; // Meetup user info

function isArray(v) {
	return v && typeof v === 'object' && typeof v.length === 'number' && !(v.propertyIsEnumerable('length'));
}

BKLET.processYQLResult = function(data)
{
	BKLET.yqlResult = data;

	BKLET.dialog = new YAHOO.widget.Dialog("dialog",
	{
		fixedcenter: true,
		visible: false,
		modal: true,
		width: '600px',
		height: '400px',
		constraintoviewport: true,
		buttons: [
		{
			text: "Close", handler: function()
			{
				this.cancel();
			}
		}]
	});
	BKLET.dialog.setHeader('YQL Query Results');
	var infoHTML = '<div id="yqlresults" style="overflow-x: hidden; overflow-y: scroll; height: 300px">';

	if (data.query.results === null) {
		infoHTML += 'Sorry, no photos';
	} else {
		infoHTML += '<div><b>Photos:</b><br/>';

		var photos = data.query.results.photo;

		if (!isArray(photos)) {
			photos = [photos];
		}

		for (var i = 0; i<photos.length; i++) {
			infoHTML += '<img src="http://farm'+photos[i].farm+'.static.flickr.com/'+photos[i].server+'/'+photos[i].id+'_'+photos[i].secret+'_m.jpg">';
		}
	}

	infoHTML += '</ul></div>';
	infoHTML += '</div>';

	BKLET.dialog.setBody(infoHTML);

	BKLET.dialog.cfg.queueProperty("keylisteners",
		new YAHOO.util.KeyListener(document, { keys:27 },
		{
			fn: function()
			{
				this.cancel();
			},
			scope: BKLET.dialog,
			correctScope: true
		}, "keyup")
	);

	BKLET.dialog.cancelEvent.subscribe(function()
	{
		BKLET.active = false;
	});

	BKLET.wait.hide();

	BKLET.dialog.render(document.body);
	BKLET.dialog.show();
};

BKLET.getYQL = function()
{
	if (BKLET.yqlResult !== null)
	{
		BKLET.processYQLResult(BKLET.yqlResult);
	}
	else
	{
		BKLET.wait.setHeader('Running YQL');
		BKLET.wait.center();
		BKLET.wait.show();

		// https://query.yahooapis.com/v1/public/yql?q=use%20'http%3A%2F%2Fwww.sergeychernyshev.com%2Fmeetup-yql%2Fmembers.xml'%20as%20members%3B%20select%20farm%2C%20server%2C%20id%2C%20secret%20from%20flickr.photos.search%20where%20text%20in%20(select%20name%20from%20members%20where%20key%3D%227f62e2a46733235403561264393830%22%20and%20group_id%20%3D%201428523)&format=xml&diagnostics=false

		YAHOO.util.Get.script("https://query.yahooapis.com/v1/public/yql?q=use%20'http%3A%2F%2Fwww.sergeychernyshev.com%2Fmeetup-yql%2Fmembers.xml'%20as%20members%3B%20select%20farm%2C%20server%2C%20id%2C%20secret%20from%20flickr.photos.search%20where%20text%20in%20(select%20name%20from%20members%20where%20key%3D%22" + BKLET.key + "%22%20and%20group_id%20%3D%20" + Chapter.id + ")%20limit%2010&format=json&diagnostics=false&callback=BKLET.processYQLResult",
		{
		    onSuccess: function(o)
		    {
			o.purge();
		    },
		    onFailure: function (o)
		    {
			o.purge();
			BKLET.wait.hide();
			BKLET.active = false;
		    },
		    onTimeout: function ()
		    {
			BKLET.wait.hide();
			BKLET.active = false;
		    },
		    timeout: 30000
		});
	}
};

BKLET.run = function()
{
	if (BKLET.active)
	{
		return;
	}
	BKLET.active = true;

	if (BKLET.key !== null)
	{
		BKLET.getYQL(BKLET.key);
	}
	else
	{
		BKLET.wait.setHeader('Retrieving Meetup API key');
		BKLET.wait.center();
		BKLET.wait.show();

		YAHOO.util.Connect.asyncRequest('GET', '/meetup_api/key/',
		{
		    success: function(o)
		    {
			BKLET.key = o.responseText.match(/<strong>(.*)<\/strong>/)[1];
			BKLET.getYQL(BKLET.key);
		    },
		    failure: function(o) {
			BKLET.wait.hide();
			BKLET.active = false;
		    },
		    timeout: 5000
		});
	}
};

BKLET.save = function(d)
{
	BKLET.data = d;
};

BKLET.progress = function()
{
	// Adding YUI skin to the body
	var b = document.getElementsByTagName('body')[0];
	YAHOO.util.Dom.addClass(b, 'yui-skin-sam');

        if (!BKLET.wait) {

            // Initialize the temporary Panel to display while waiting for the rest of the libraries to load
            BKLET.wait = 
                    new YAHOO.widget.Panel("wait", 
                                                    { width: "290px", 
                                                      fixedcenter: true, 
                                                      close: false, 
                                                      draggable: false, 
                                                      zindex:4,
                                                      modal: true,
                                                      visible: false
                                                    } 
                                                );
    
            BKLET.wait.setHeader("Loading YUI components, please wait...");
            BKLET.wait.setBody("<div style=\"text-align: center\"><img src=\"http://us.i1.yimg.com/us.yimg.com/i/us/per/gr/gp/rel_interstitial_loading.gif\"/></div>");
            BKLET.wait.render(document.body);
		// Show the Panel
		BKLET.wait.show();
        }

	// let's load the rest of things
	(new YAHOO.util.YUILoader({

	    // Identify the components you want to load.  Loader will automatically identify
	    // any additional dependencies required for the specified components.
	    require: ['get', 'dragdrop', 'event'],

	    // Configure loader to pull in optional dependencies.  For example, animation
	    // is an optional dependency for slider.
	    loadOptional: true,

	    // The function to call when all script/css resources have been loaded
	    onSuccess: BKLET.run,

	    // Configure the Get utility to timeout after 10 seconds for any given node insert
	    timeout: 10000,

	    // Combine YUI files into a single request (per file type) by using the Yahoo! CDN combo service.
	    combine: true
	})).insert();
};

// let's load minimal set to show the progress bar
(new YAHOO.util.YUILoader({

    // Identify the components you want to load.  Loader will automatically identify
    // any additional dependencies required for the specified components.
    require: ["container", "dom"],

    // Configure loader to pull in optional dependencies.  For example, animation
    // is an optional dependency for slider.
    loadOptional: true,

    // The function to call when all script/css resources have been loaded
    onSuccess: BKLET.progress,

    // Configure the Get utility to timeout after 10 seconds for any given node insert
    timeout: 10000,

    // Combine YUI files into a single request (per file type) by using the Yahoo! CDN combo service.
    combine: true
})).insert();
