// $Id: myweb.js 1035 2009-10-14 09:03:01Z sdalu $

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

String.format = function(format){
    var args = $.makeArray(arguments, 1);
    return format.replace(/\{(\d+)\}/g, function(m, i) {
	    return args[i]; });
};
	    



if (typeof(Ext) != 'undefined')
    Ext.BLANK_IMAGE_URL = '/ext/resources/images/default/s.gif';


MyWEB = {};

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


//----------------------------------------------------------------------
// Language switching by cookie
//   => In menu language, don't follow links but set cookie for
//      language preference and reload current page
//----------------------------------------------------------------------
MyWEB.lang_switch_by_cookie = function() {
    if (! $.cookies) return;
    $('#m-menu-lang a').live('click', function(e) {
	var lang = $(this).closest('a').attr('hreflang');
	if (lang) $.cookies.set('language', lang, {
	  	        domain     : MyWEB.cookie.domain,
		        path       : '/',
		        hoursToLive: MyWEB.cookie.expires });
	else      $.cookies.del('language');
	e.preventDefault();
	window.location.reload();
    });
};

//----------------------------------------------------------------------
// 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
 */
MyWEB.closable = function(box_id, close_id, opts) {
    opts = $.extend({
	    key       : null,
	    expires   : null,
	    start     : 0,
	    autoclose : 0,
	    show      : 'always' }, opts || {});

    var box          = $('#' + box_id);
    var btn          = $('#' + close_id);
    var cookies_opts = {};

    if (opts.key)
	cookies_opts.hoursToLive = opts.expires ? opts.expires 
	                                        : MyWEB.cookie.expires;

    if ($.cookies && opts.key && $.cookies.get(opts.key)) {
	box.remove();
	return;
    }

    var remaining = null;
    var closer    = $.task(function() {
        if (remaining) {
	    remaining.cancel();
	    remaining = null;
	}
	box.hide('drop', { direction: 'up', 
			   easing   : 'easeOutQuad' }, 200);
	if ($.cookies) $.cookies.set(opts.key, false);
    });
    
    if (btn.length)
	btn.one('click', function() { closer.now(); });

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

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

    if (opts.start > 0) {
	box.hide();
	box.removeClass('m-hidden');
	$.task(function() { 
	    box.slideDown(500, do_autoclose); }).delay(opts.start * 1000);
    }  else {
	do_autoclose();
    }
};


//----------------------------------------------------------------------
// Bookmark me
//----------------------------------------------------------------------
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 = String.format(info.url, url, title);
	var width  = info.width  || 500;
	var height = info.height || 500;
	var opt    = String.format('width={0},height={1},toolbar=0,status=0,resizable=1', width, height);

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

    return {
    init: function(id) {
	win = id;
	$('[id='+id+'] [id^='+id+'-]').each(function() {
	    var tag = this.id.substring(id.length+1);
	    $(this).bind('click', function() {
		bookmark(tag, document.location, document.title); });
        });
    }
    };
};


//----------------------------------------------------------------------
//
//----------------------------------------------------------------------
MyWEB.message = function() {
    var msgs   = [];
    var box, msg, active;

    var update = function() {
	msg.attr('href', active.url).html(active.text).fadeIn();
    };

    var showmsg = function(idx) {
	if (msg.is('.hover')) return;
	active = msgs[idx];
	if (msg.is(':visible')) msg.fadeOut('normal', update);
	else update(); 
    };

    return {
    init  : function(id) {
	box = $('#' + id);
	msg = $('<a/>').addOnClassOver('hover').appendTo(box);            },
    start : function(msec) {
        var index = 0;
	showmsg(0);
	setInterval(function() {
	   showmsg(index = msgs[index+1] ? index+1 : 0); }, msec);        },
    add   : function(cfgs) {
        $.each(cfgs, function() { if (this == '-') msgs = [];
		                  else             msgs.push(this); });   },
    clear : function() {
	msgs = [];                                                        }
    };
};


//----------------------------------------------------------------------
//
//----------------------------------------------------------------------
MyWEB.menutab = function() {
    var delay    = 300;
    var shown    = null;
	
    var hideTask = $.task(function() {
	if (shown) { shown.hide(); shown = null; }
    });

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

        tab.hover(
            function() { if (shown == sub) { hideTask.cancel(); } 
		         else              { hideTask.now();
			                     sub.css({top: 2, left: 0}).show();
					     shown = sub; } },
	    function() { hideTask.delay(delay); });
	}
    };
};


//----------------------------------------------------------------------
//
//----------------------------------------------------------------------
MyWEB.search = function() {
    /*
    var store   = null;
    var search_tab = null;
    var search_win      = null;
    var win     = null;

    var tplWebNews = new Ext.XTemplate(
	'<tpl for=".">',
        '<div class="entry">',
	    '<h1><a rel="bookmark" href="{clickurl}">{title}</a></h1>',
	    '<div class="excerpt">{abstract}</div>',
	    '<h4>{size:fileSize} | {date:date("F j, Y")}</h4>',
	 '</div>',
	'</tpl>');

    */
    return { 
    init: function(el, width) {
	    /*
	Ext.get(el).dom.innerHTML = '<div id="menu-search"></div>';
	el = Ext.get('menu-search');

	store = new Ext.data.Store({
	    proxy : new Ext.data.HttpProxy({
		url: '/lib/ajax/search.php' }),
	    reader: new Ext.data.JsonReader({
		root         : 'results',
		totalProperty: 'total',
		id           : 'id'
	      }, [ 'title', 'abstract', 'url', 'clickurl',
		   'size', 'date', 'dispurl', 'thumbnail_url'])
	  });
  

	search_tab = new Ext.form.TriggerField({
	    width        : width,
	    triggerClass :'x-form-search-trigger',
	    renderTo     : el,
	    emptyText    : 'Search...',
	    stateful     : true,
	    stateEvents  : [ 'change' ],
	    stateId      : 'search',
	    getState     : function() {
	       return { value: this.getRawValue() }; },
	    selectOnFocus: true,
	    listeners    : {
		'specialkey': function(f, e) {
		    if ((e.getKey() == e.ENTER) || (e.getKey() == e.RETURN))
			this.onTriggerClick(e);
		}
	      },
	    onTriggerClick : function(e) {
		var v = this.getRawValue();
		if (v.length < 1) {
		    store.removeAll()
		} else if (v.length < 2) {
		    Ext.Msg.alert('Invalid Search',
				  'You must enter a minimum of 2 characters');
		} else {
		    store.baseParams['query'] = v;
		    store.reload({params:{start: 0}});
		    search_win.setValue(v);
		    win.doSize(Ext.lib.Dom.getViewWidth(),
			       Ext.lib.Dom.getViewHeight());
		    win.show(this);
		}
	      }
	  });

	 search_win = new Ext.form.TriggerField({
	    selectOnFocus: true,
	    allowBlank: false,
	    minLength: 2,
	    triggerClass :'x-form-search-trigger',
	    listeners: {
		    'specialkey' : function(f,e){
			if (e.getKey() == e.RETURN || e.getKey() == e.ENTER) {
			this.onTriggerClick(e);
			} }
		 },
	    onTriggerClick : function(e) {
		     if (!this.isValid())
			 return;
		     store.baseParams['query'] = this.getValue();
		store.reload({params:{start: 0}});
	      }
	    });
	win = new Ext.Window({
	    id            : 'menu-search-win',
	    defaults      : { stateful: false },
	    title         : 'Search results',
	    closeAction   : 'hide',
	    modal         : true,
	    resizable     : false,
	    draggable     : false,
	    plain         : false,
	    autoScroll    : true,
	    items         : new Ext.DataView({
		loadingText : 'Searching...',
	        store       : store,
		itemSelector: '.search-entry',
		tpl         : tplWebNews
	      }),
	    bbar          : new Ext.PagingToolbar({
		pageSize   : 30,
		store      : store,
		displayInfo: true,
		displayMsg : '{0} - {1} of {2}',
		emptyMsg   : "No Results",
		items      : [ '-', search_win ]
	      }),
	    listeners: {
		'beforehide': function() {
		    search_tab.setRawValue(search_win.getRawValue());
		  }
	      }
	    });
	win.render(Ext.getBody());
	win.doSize = function(width, height) {
	    var w = width  - 100, h = height - 100;
	    if (w < 400) w = 500;
	    if (h < 200) w = 300;
	    
	    var p = Ext.getBody().getScroll();
	    var x = (width-w)/2,  y = (height-h)/2
	    if (x < 0) x = 0;
	    if (y < 0) y = 0;

	    win.setPosition(p.left + x, p.top + y);
	    win.setSize(w, h);
	  }

	Ext.EventManager.onWindowResize(function(width, height) {
		if (win.isVisible)
		    win.doSize(width, height);
	    });

	    */
      }
    }
  };



$(function(){
    if ($.coookies)
	$.cookies.setOptions(MyWEB.cookie);

    $('form.auto-clear input[type=text]').each(function() {
	var el = $(this);
	if (el.val().length)
	    el.attr('rel', el.val()).addClass('m-blurred');

	el.bind('focus', function() {
	    if (el.val() == el.attr('rel'))
		el.val('').removeClass('m-blurred'); });
	el.bind('blur', function(){
	    if (el.val() == '')
		el.val(el.attr('rel')).addClass('m-blurred'); });
    });

});


$(function() {
    $('.m-button').each(function() { this.unselectable = 'on'; });
});
