/*
** WorldServe.js	- JavaScript library used by WorldServe client sites
**
** Copyright (c) WorldServe Internet Services
** All Rights Reserved
** For more information, see http://WorldServe.com/copyright
**
*/

// simple utility functions to determine variable types
function is_type(variable, type)
{
    return ((typeof variable) == type);
}
/*
// Google Analytics fails if a function named 'undefined' exists
function undefined(variable)
{
    return is_type(variable, 'undefined');
}
*/
var defined = function defined(variable)
{
/*
    return !undefined(variable);
*/
    return !is_type(variable, 'undefined');
}

function is_null(variable)
{
    return (variable === null);
}

function is_string(variable)
{
    return is_type(variable, 'string');
}

function is_function(variable)
{
    return is_type(variable, 'function');
}

function is_object(variable)
{
    return is_type(variable, 'object');
}

function empty(variable)
{
    var re  = new RegExp("^\s*$");
    return (!defined(variable)) || (re.exec(variable) != null);
}

function IE()
{
    /* for Internet Explorer */
    /*@cc_on @*/
    /*@
    return true;
    @*/

    return false;
}

// from http://msdn.microsoft.com/en-us/library/ms537509(VS.85).aspx
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or false
// (indicating the use of another browser).
{
    /* for Internet Explorer */
    /*@cc_on @*/
    /*@
    if (navigator.appName == 'Microsoft Internet Explorer')
    {
	var ua = navigator.userAgent;
	var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	if (re.exec(ua) != null)
	{
	    return parseFloat( RegExp.$1 );
	}
    }
    @*/

    return false;
}

function br2nl(string)
{
    return string.replace(/ *<br *\/?> */, '\n');
}

// based on the PHP function
// (wish JavaScript did it intrinsically)
function strip_tags(string)
{
    return string.replace(/<([^>]+)>/g, '');
}

// (wish JavaScript had an equivalent for html_entity_decode)
function html_entity_decode(string)
{
var textarea = document.createElement('textarea');
    /*
    // THANK YOU http://www.locomotive.com.au/java/new/new42.htm !
    // original:
    // textarea.innerHTML = str.replace(/</g,"<").replace(/>/g,">");
    // not sure why the replace calls ?
    */
    textarea.innerHTML = string;

    return textarea.value;
}

var WorldServe = function WorldServe(client)
{
    var W = WorldServe;	// shorthand for member functions

    YUI(W.YUIconf).use('*', function(Y)
    {
	WorldServe.Y = Y;
	Y.Node.addMethod('setID', function(_node, id)
	{
	    var node = Y.one(_node);

	    var oldElement = Y.one('#' + id);
	    if(oldElement != null)
	    {
		oldElement.resetID();
	    }

	    node.saveID(id);
	    node.set('id', id);
	});

	Y.Node.addMethod('saveID', function(_node, id)
	{
	    var node = Y.one(_node);

	    if (node.hasAttribute('id') && (node.getAttribute('id') != id))
	    {
		node.setAttribute('id_save', node.getAttribute('id'));
	    }
	});

	Y.Node.addMethod('resetID', function(_node)
	{
	    var node = Y.one(_node);

	    if (node.hasAttribute('id_save'))
	    {
		node.setAttribute('id', node.getAttribute('id_save'));
	    }
	    else
	    {
		node.removeAttribute('id');
	    }
	});

	Y.Node.addMethod('enhancedStatus', function()
	{
	    var message = null;

	    if (this.hasAttribute('title'))
	    {
		message = this.getAttribute('title');
	    }
	    else if (this.hasAttribute('alt'))
	    {
		message = this.getAttribute('alt');
	    }
	    else if (this.get('tagName').toLowerCase() == 'a')
	    {
		message = this.getAttribute('text');
	    }

	    var status = null;
	    if (message != null)
	    {
		status = html_entity_decode(strip_tags(message));

		if (status != '')
		{
		    window.status = status;
		}
	    }

	    return status;
	});

	function enhancedMouseOver(event)
	{
	    try
	    {
		this.enhancedStatus();

		event.preventDefault();
		//event.stopPropagation();
	    }
	    catch (err) {}
	}

	function enhancedMouseMove(event, x, y)
	{
	    this.enhancedStatus();

	    event.preventDefault();
	    //event.stopPropagation();
	}

	function enhancedMouseOut(event)
	{
	    window.status = null;
	    return true;
	}

	W.alertTitle = function alertTitle()
	{
	    //link = this; //event.srcElement;
	    //var title = enhancedStatus(this);

	    //alert(title);
	    //alert(enhancedStatus(this));
	    alert(this.enhancedStatus());
	}

	function isPopUp()
	{
	    return (document.body.className == window.name);
	}

	function blurClose()
	{
	    // blur hides the window immediately, faster than close
	    // gives user a better experience
	    window.blur();
	    window.close();
	    return false;
	}

	function resizeToFit()
	{
	    // push it back to work behind the scenes
	    //window.blur();

	    //resize to width
	    var photograph = Y.one('#photograph');
	    var width = photograph.width + 50;
	    var height = document.body.scrollHeight + 80;
	    window.resizeTo(width, height);

	    // center window
	    var left = Math.round((screen.width - width) / 2);
	    var top = Math.round((screen.height - height) / 2);
	    window.moveTo(left, top);

	    // bring it forward to be seen
	    window.focus();
	}

	ajax2text = function(rawXML)
	{
	    var content = rawXML.replace(ajax2text.pattern, '$1');
	    var trimmed = content.replace(ajax2text.trim, '$1');
	    return trimmed;
	    //return Y.one('body').create(trimmed);
	}
	ajax2text.pattern = new RegExp('(?:<\\?xml.*\\?>)?\\s*<\\s*ajax[^>]*>\\s*((?:\\s*<.*>)*)\\s*<\\s*\/ajax\\s*>', 'img');
	ajax2text.trim = new RegExp('^\\s*(<.*>)\\s*$', 'img');

// Language selection in multilingual documents
	var setLang = function(lang)
	{
	    if (document.documentElement.lang != lang)
	    {
		var link = Y.one('link[hreflang=' + lang + ']');	// only if an edition in this language is already identified
		if (link !== null)
		{
		    document.documentElement.lang = lang;

		    document.title = link.getAttribute('title');
		}

		Y.all('select.lang').set('value', lang).set('lang', lang);	// setting the language on the select element forces the font on Firefox (tlh)
	    }
	}

	var selectLang = function(event)
	{
	    var target = event.currentTarget;
	    var lang = (target.get('tagName').toLowerCase() == 'a') ? target.getAttribute('hreflang') : target.get('value');
	    setLang(lang);

	    // requires YUI Cookie module
	    try	// fails in IE8
	    {
		Y.Cookie.set('lang', lang, { path: '/', expires: new Date('2345') });
	    }
	    catch(err) {}

	    try	// fails in IE8
	    {
		//event.preventDefault();
		event.halt();
	    }
	    catch(err)
	    {
		event._event.returnValue = false;
	    }
	}

	Y.all('ul.lang').each(function (node) {node.delegate('click', selectLang, 'a.lang')});
	Y.all('select.lang').on('change', function (event) {selectLang(event);});

/*
**
**	Google Analytics
**
*/

	var googleAnalytics =
	W.googleAnalytics = function googleAnalytics(account)
	{
	    if (arguments.length > 1)
	    {
		var i;
		for(i = 0; i < arguments.length; ++i)
		{
		    googleAnalytics(arguments[i]);
		}
	    }

	    return googleAnalytics.asynchronously ? googleAnalytics.asynchronous(account) : googleAnalytics.synchronous(account);
	}

	googleAnalytics.synchronous = function(account)
	{
	    Y.after('load', Y.use('googleAnalytics', function(Y)
	    {
		try
		{
		    var pageTracker = _gat._getTracker(account);
		    pageTracker._trackPageview();
		    Y.log('googleAnalytics (synchronous) - ' + account);
		}
		catch(err) {}
	    }));
	}

	googleAnalytics.asynchronous = function(account)
	{
	    _gaq.push(['_setAccount', account]);
	    //_gaq.push(['_setDomainName', 'healingtimefoundation.org']);
	    _gaq.push(['_setAllowLinker', true]);
	    _gaq.push(['_trackPageview']);

	    Y.after('load', Y.use('googleAnalytics', function(Y)
	    {
		Y.log('googleAnalytics (asynchronous) - ' + account);
	    }));
	}

	googleAnalytics.asynchronously = true;

	//todo: move initializations to handler function
	Y.on('domready', function()
	{
	    Y.all('a.external, a.WorldServe').each(function(node)
	    {
		var target = 'external';

		var targets = W.targets;
		for(var i in targets)
		{
		    if(node.hasClass(targets[i]))
		    {
			target = targets[i];
			break;
		    }
		}

		node.set('target', target);
	    });

	    Y.all('a').each(function(node)
	    {
		node.on('mouseover',	enhancedMouseOver);
		node.on('focus',	enhancedMouseOver);

		node.on('mouseout',	enhancedMouseOut);
		node.on('blur',		enhancedMouseOut);
	    });

	    Y.all('area').each(function(node)
	    {
		node.on('mouseover',	enhancedMouseOver);
		node.on('focus',	enhancedMouseOver);

		node.on('mouseout',	enhancedMouseOut);
		node.on('mousemove',	enhancedMouseMove);
	    });

	    Y.all('.alert').each(function(node)
	    {
		node.on('click',	W.alertTitle);
	    });

	    Y.all('#close').each(function(node)
	    {
		if (isPopUp())
		{
		    node.setContent("close");
		    node.set('title', "close");

		    node.on('click', blurClose);
		}
	    });

	    if (defined(client) && is_function(client.onload))
	    {
		client.onload();
	    }

	    Y.all('#gigya-socialize-share-bar').each(W.gigya.shareBar);	//todo .one().each?
	    Y.all('.social .gigya-socialize-follow-bar').each(W.gigya.followBar);
	});

	if (is_function(client))
	{
	    client(Y, W);
	}

	Y.after('load', googleAnalytics.meta);
    });
}

WorldServe.Y = null;
WorldServe.YUIconf =
    {
	timeout: 10000,
	modules:
	    {
		googleAnalytics:
		{
		    fullpath: ((document.location.protocol == 'https:') ?
				'https://ssl.google-analytics.com/ga.js' :
				'http://www.google-analytics.com/ga.js')
		},

		firebug:
		{
		    fullpath: ('https://getfirebug.com/firebug-lite.js')
		},

		gigya:
		{
		    fullpath:	'http://cdn.gigya.com/js/socialize.js'
/*
		},

		twitter_anywhere:
		{
		    fullpath: ('http://platform.twitter.com/anywhere.js?id=y0e1mh3kjgpK8T5XL2kwg&amp;v=1')
		},

		twitter_widget:
		{
		    fullpath: ('http://widgets.twimg.com/j/2/widget.js')
*/
		}
	    }
    };

/*
**
**	Gigya Socialize tools
**
*/

WorldServe.gigya =
{
    APIKey:	null,

    setAPIKey:	function setAPIKey(APIKey)
    {
	var W	= WorldServe;
	var G	= W.gigya;
	G.APIKey= APIKey;

	W.YUIconf.modules.gigya.fullpath	= 'http://cdn.gigya.com/js/socialize.js?apiKey=' + WorldServe.gigya.APIKey;
    },


    followBar:	function followBar(node)
    {
	var W = WorldServe;
	var Y = W.Y;
	var G = W.gigya;

	var id = node.generateID();

	var showFollowBarUI_params =
	{
	    containerID:	id,
	    iconSize:	22,
	    buttons:	[]
	}

	node.ancestor('.social').all('li').each(
	    function(social)
	    {
		var a = social.one('a');

		switch(social.get('className'))
		{
		    case 'Facebook':
			showFollowBarUI_params.buttons.push(
			{
			    provider:	'facebook',
			    action:		'dialog',
			    actionURL:	a.get('href')
			});
			G.replaceNode(a, '#' + id + '_btn_facebook');
			break;

		    case 'Twitter':
			showFollowBarUI_params.buttons.push(
			{
			    provider:	'twitter',
			    action:		'dialog',
			    followUsers:	a.get('href').replace(/^.*[/]/, ''),
			    title:		a.get('title')
			});
			G.replaceNode(a, '#' + id + '_btn_twitter');
			break;
		}
	    });

	Y.use('gigya', function()
	{
	    var conf =
	    {
		APIKey: G.APIKey
	    }
	    gigya.services.socialize.showFollowBarUI(conf, showFollowBarUI_params);
	});
    },

    shareBar: function shareBar(node)
    {
	var W = WorldServe;
	var Y = W.Y;
	var G = W.gigya;

	Y.use('gigya', function()
	{
	    var gigyaUA = new gigya.services.socialize.UserAction();
	    gigyaUA.setTitle(document.title);
	    gigyaUA.setLinkBack(document.location.href);
	    var metaDescription = Y.one('meta[name=description]');
	    if (metaDescription != null)
	    {
		gigyaUA.setDescription(metaDescription.get('content'));
	    }
	    gigyaUA.addActionLink("Read More", document.location);

	    var showShareBarUI_params =
	    {
		userAction:	gigyaUA,
		containerID:	node.get('id'),
		//cid:		'', // context ID; see http://developers.gigya.com/030_API_reference/010_Client_API/010_Objects/Conf_object
		operationMode:	'multiSelect',
		enabledProviders:'Facebook,Twitter,MysPace,Orkut,LinkedIn,Google,Yahoo,Messenger',
		disabledProviders:'vznet,renren,kaixin,vkontakte',
		moreDisabledProviders:'vznet,renren,kaixin,vkontakte',
		showEmailButton:true,
		emailProviders:	'Yahoo,Google,AOL,Orkut,Hi5',
		shortURLs:	'whenRequired',
		showCounts:	'bottom',

		shareButtons:
		    [
			{	// General Share Button
			    provider:	'share',
			    enableCount:false,
			    emailProviders:	'Yahoo,Google,AOL,Orkut,Hi5'
			},
			{	// Email button
			    provider:	'email',
			    enableCount:false
			},
			{	// Twitter Tweet button
			    provider:	'Twitter-Tweet',
			    enableCount:false
			},
			{	// Google Plus-One button
			    provider:	'Google-PlusOne',
			    enableCount:false
			},
			{	// Digg button
			    provider:	'Digg',
			    enableCount:false
			},
			{	// Delicious button
			    provider:	'Delicious',
			    enableCount:false
			},
			{	// StumbleUpon button
			    provider:	'StumbleUpon',
			    enableCount:false
			},
			{
			    provider:	'Facebook-Like',
			    action:	'recommend',
			    enableCount:true	// otherwise "be the first..." breaks the formatting
			    //enableCount:	true,
			}
		    ]
	    }

	    var conf=
	    {
		APIKey: G.APIKey
	    }

	    gigya.services.socialize.showShareBarUI(conf, showShareBarUI_params);
	});
    },

    replaceNode: function(oldNode, newNodeID)
    {
	var W = WorldServe;
	var Y = W.Y;
	var css_selector = '.gig-followbar a[href="' + oldNode.get('href') + '"]';

	Y.on('contentready', function(){
			    oldNode.replace(this);
			}, css_selector);
    }
}
WorldServe.targets = Array('WorldServe');

// for Google Analytics
var _gaq = _gaq || [];	// must be defined in global scope

// for debugging
function loaded(Y)
{
    var used = [];
    Y.each(Y.Env._attached, function(v, k)
    {
	used[used.length] = k;
    });
    Y.log(used);
}

