// $Id: myweb.js 1234 2009-11-12 15:20:36Z sdalu $

//
// Copyright (c)  Stephane D'Alu  2008-2009
// http://www.sdalu.com/
//


(function() {


var MyWEB = { 
    opts:  { cookie : { domain  : null,
			expires : null,
			path    : null },
	     lang   : null }
};



YUI.add('myweb', function(Y) {


Y.namespace('MyWEB');

Y.MyWEB.opts = MyWEB.opts;


//----------------------------------------------------------------------
// Set options for:
//  - cookie (expires, path, domain)
//  - lang
//----------------------------------------------------------------------
Y.MyWEB.setOptions = function(opts) {
    if (!opts) return;
    for (var prop in opts)
	switch (prop) {
	case 'lang':
	    Y.MyWEB.opts[prop] = opts[prop];
	    break;
	case 'cookie':
	    Y.MyWEB.opts[prop] = Y.merge(Y.MyWEB.opts[prop], opts[prop]);
	    break;
	}
};



//----------------------------------------------------------------------
// Language switching by cookie
//   => In menu language, don't follow links but set cookie for
//      language preference and reload current page
//----------------------------------------------------------------------
Y.MyWEB.lang_switch_by_cookie = function(id) {
    if (! Y.Cookie) return;
    Y.all('#'+id + ' a').on('click', function(evt) {
	evt.preventDefault();

	var key  = 'language';
	var lang = evt.target.closest('a').getAttribute('hreflang');
	if (lang.length) Y.Cookie.set(key, lang, {
		             domain : Y.MyWEB.opts.cookie.domain,
		             path   : '/',
		             expires: Y.MyWEB.opts.cookie.expires });
	else
	    Y.Cookie.remove(key);
	window.location.reload();
 });
};



//----------------------------------------------------------------------
// Mark all button (.m-button) as unselectable
//----------------------------------------------------------------------
Y.MyWEB.make_button = function() {
    Y.all('.m-button').each(function(elt) { 
	Y.Node.getDOMNode(elt).unselectable = 'on'; });
};



//----------------------------------------------------------------------
// Prefill form with an HINT on desired content
//   => Form is selected with the .m-hinted class, 
//       and blurring done with the .m-blurred class.
//----------------------------------------------------------------------
Y.MyWEB.hinted_form = function() {
    Y.all('form.m-hinted input[type=text]').each(function(el) {
	// Save hint
        if (el.get('value').length)
	    el.setAttribute('rel', el.get('value')).addClass('m-blurred');
	// Act on focus/blur
        el.on('focus', function() {
	    if (el.get('value') != el.getAttribute('rel')) return;
	    el.set('value','').removeClass('m-blurred');	          });
        el.on('blur', function(){
	    if (el.get('value') != '') return;
	    el.set('value',el.getAttribute('rel')).addClass('m-blurred'); });
    });
};



//----------------------------------------------------------------------
// Bookmark me
//----------------------------------------------------------------------
Y.MyWEB.bookmarkme = function() {
    var win = null;
    var db  = { 
	'facebook'   : {
	    url: 'http://www.facebook.com/sharer.php?u={0}&t={1}',
	    width: 626, height: 436 },
	'myspace'    : { 
	    url: 'http://www.myspace.com/index.cfm?fuseaction=postto&u={0}&t={1}' },
	'delicious'  : {
	    url: 'http://delicious.com/save?v=5&noui&jump=close&url={0}&title={1}',
	    width: 550, height: 550 },
	'reddit'     : {
	    url: 'http://reddit.com/submit?url={0}&title={1}' },
	'stumbleupon': {
	    url: 'http://www.stumbleupon.com/submit?url={0}&title={1}' },
	'digg'       : {
	    url: 'http://digg.com/submit?url={0}&title={1}' },
	'google'     : {
	    url: 'http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk={0}&title={1}',
	    width: 550, height: 420 },
	'yahoo'      : {
	    url: 'http://bookmarks.yahoo.com/toolbar/savebm?u={0}&t={1}&opener=bm&ei=UTF-8',
	    width: 450, height: 480 }
    };
    var bookmark = function(type, url, title)  {
	url   = url   ? encodeURIComponent(url)   : null;
	title = title ? encodeURIComponent(title) : null;
	var info = db[type];
	if (!info) {
	    alert('Bookmarking on ' + type + 'is unsupported');
	    return;
	}
	var submit = Y.substitute(info.url, {0: url, 1: title});
	var opt_s  = 'width={0},height={1},toolbar=0,status=0,resizable=1';
	var opt    = Y.substitute(opt_s, { 0: info.width  || 500, 
					   1: info.height || 500 });

	window.open(submit, win, opt);
    };

    return {
    init: function(id) {
	win = id;
	Y.all('[id='+id+'] [id^='+id+'-]').each(function(mark) {
	    var tag = mark.get('id').substring(id.length+1);
	    mark.on('click', function() {
		bookmark(tag, document.location, document.title); });
        });
    }
    };
};



//----------------------------------------------------------------------
// Display short messages
//----------------------------------------------------------------------
Y.MyWEB.message = function() {
    var msgs   = [];
    var msg, active;

    var update  = function() {
	msg.setAttribute('href', active.url).setContent(active.text)
	   .ez.fadeIn();
    };

    var showmsg = function(idx) {
	if (msg.test('.hover')) return;
	active = msgs[idx];
	if (msg.ez.isVisible()) msg.ez.fadeOut({ callback: update });
	else update(); 
    };

    return {
    init  : function(id) {
	msg = Y.Node.create('<a/>').plug(Y.Plugin.EasyNode);
	msg.on('mouseenter', function() { msg.addClass('hover');    });
	msg.on('mouseleave', function() { msg.removeClass('hover'); });
	Y.one('#' + id).append(msg);					  },
    start : function(msec) {
        var index = 0;
	showmsg(0);
	setInterval(function() {
	   showmsg(index = msgs[index+1] ? index+1 : 0); }, msec);        },
    add   : function(cfgs) {
        Y.each(cfgs, function(cfg) { if (cfg == '-') msgs = [];
		                     else            msgs.push(cfg); });  },
    clear : function() {
	msgs = [];                                                        }
    };
};



//----------------------------------------------------------------------
// Handle menu
//----------------------------------------------------------------------
Y.MyWEB.menutab = function() {
    var delay    = 300;
    var shown    = null;
	
    var hideTask = function() { 
	if (shown) { shown.ez.hide(); shown = null; } };

    var later = null;

    return {
    attach: function(name){
	var tab  = Y.one('#menu-tab-'+name);
	var sub  = Y.one('#menu-sub-'+name);
	if (!tab || !sub) return;

	sub.plug(Y.Plugin.EasyNode);

        tab.on('mouseenter', function() {
	    if (later) later.cancel(); 
	    if (shown == sub) return;
	    hideTask();
	    sub.setStyles({ left: 0, top: '2px' });
	    sub.ez.show();
	    shown = sub; });
	tab.on('mouseleave', function() {
	    if (later) later.cancel();
	    later = Y.later(delay, null, hideTask); });
	}
    };
};



//----------------------------------------------------------------------
// Closable box
//----------------------------------------------------------------------

/*
 * box_id   : id of the element container
 * close_id : id of the element used as close button
 * opts     : options
 *   - key      : cookie key
 *   - expires  : cookie expiration in hours
 *   - start    : only show notify after 'start' seconds
 *   - autoclose: secondes before automatically closing
 *   - show     : hover = when hovering box_id
 *                *     = always on
 */
Y.MyWEB.closable = function(box_id, close_id, opts) {
    opts = Y.merge({
	    key       : null,
	    expires   : null,
	    start     : 0,
	    autoclose : 0,
	    show      : 'always' }, opts || {});

    var box          = Y.one('#' + box_id  ).plug(Y.Plugin.EasyNode);
    var btn          = Y.one('#' + close_id);

    if (Y.Cookie && opts.key && Y.Cookie.get(opts.key)) {
	box.remove();
	return;
    }

    var remaining = null;
    var closer    = Y.task(function() {
        if (remaining) {
	    remaining.cancel();
	    remaining = null;
	}
	box.ez.hide();
       
	if (Y.Cookie && opts.key) {
	    var cookie_opts = {};
	    if (opts.expires) cookie_opts.expires = opts.expires;
	    cookie_opts = Y.merge(Y.MyWEB.opts.cookie, cookie_opts);
	    Y.Cookie.set(opts.key, false, cookie_opts);
	}
    });
    
    if (btn) {
	btn.on('click', closer.now, closer);

	switch(opts.show) {
	case 'hover':
	    btn.ez.hide();
	    box.removeClass('m-hidden');
	    box.on('mouseenter', btn.ez.fadeIn,  btn.ez);
	    box.on('mousleave',  btn.ez.fadeOut, btn.ez);
	    break;
	}
    }

    function do_autoclose() {
	if (opts.autoclose <= 0) return;
	if (btn) {
	    remaining = Y.repeat(function() {
		var sec = opts.autoclose - this.count();
                btn.all('.m-autoclose-value').setContent(sec.toString()) });
	    remaining.start(1000, opts.autoclose);
	}
	closer.delay(opts.autoclose * 1000);
    }

    if (opts.start > 0) {
	box.ez.hide();
	box.removeClass('m-hidden');
	Y.task(function() { 
		box.ez.fadeIn({ callback: do_autoclose}); 
	    }).delay(opts.start * 1000);
    }  else {
	do_autoclose();
    }
};




}, '0.2.0', {
    requires: [ 'node', 'selector-css3',
		'event-delegate', 'event-focus', 'event-mouseenter',
		'substitute',
		'easy-node', 'node-extra', 'task'],
    optional: [ 'cookie' ] 
});



}());