/*
 * zoolib.js
 *
 * Javascript library for zoo.gr
 */

Zoo = window.Zoo || {};

Zoo.Event = window.Zoo.Event || {
	_handlers: {},

	subscribe: function(event, handler) {
		if(!this._handlers[event])
			this._handlers[event] = [];
		this._handlers[event].push(handler);
	},

	_fire: function(event) {
		var handlers = this._handlers[event];
		if(!handlers) return;

		var i;
		for(i = 0; i < handlers.length; i++)
			handlers[i]();
	}
};

Zoo.FB = window.Zoo.FB || {
	_inited: false,
	_onWindowBlock: null,

	_appId: null,
	_useXfbml: null,
	_forcePopup: null,

	// we wrap window.open to detect if a window is blocked
	_window_open: function(url, name, specs, replace) {
		// NOTE: this = window
		var handler = window._fb_open(url, name, specs, replace);

		var blocked = !handler || handler.closed || typeof handler.closed == 'undefined';
		if(blocked && Zoo.FB._onWindowBlock)
			Zoo.FB._onWindowBlock();
		Zoo.FB._onWindowBlock = null;

		return handler;
	},

	// loads facebook library
	init: function(options) {
		this._appId = options.appId;
		this._useXfbml = options.useXfbml;
		this._forcePopup = options.forcePopup;

		// this is called by facebook after initialization
		window.fbAsyncInit = function() {
			FB.init({
				appId  : Zoo.FB._appId,		// must be set in the page the loads this script
				status : false,				// check login status
				cookie : true,				// enable cookies to allow the server to access the session
				xfbml  : Zoo.FB._useXfbml	// parse XFBML, must be set in the page the loads this script
			});

			window.fbAsyncInit = null;
			Zoo.FB._inited = true;

			Zoo.Event._fire('Zoo.FB.init');
		};

		// this loads the library
		var e = document.createElement('script');
		e.src = document.location.protocol + '//connect.facebook.net/el_GR/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	},

	login: function(resultHandler) {
		if(!this._inited) {
			this._sendResult(resultHandler, { status: 'not_inited' });
			return;
		};

		this._onWindowBlock = function() {
			this._sendResult(resultHandler, { status: 'blocked' });
		};
		FB.login(function(response) {
			Zoo.FB._onWindowBlock = null;
			var res = { status: response.session ? 'ok' : 'cancelled' };
			Zoo.FB._sendResult(resultHandler, res);
		});
	},

	refreshLoginState: function(resultHandler) {
		if(!this._inited) {
			this._sendResult(resultHandler, { status: 'not_inited' });
			return;
		};

		FB.getLoginStatus(function(response) {
			var res = { status: 'ok' };
			Zoo.FB._sendResult(resultHandler, res);
		}, true); // force
	},

	getEmailPermission: function(resultHandler) {
		if(!this._inited) {
			this._sendResult(resultHandler, { status: 'not_inited' });
			return;
		};

		var opt = { perms: 'email' };

		this._onWindowBlock = function() {
			this._sendResult(resultHandler, { status: 'blocked' });
		};
		FB.login(function(response) {
			Zoo.Util.log('FB.login response', response);

			Zoo.FB._onWindowBlock = null;
			var gotPerm = response.perms && response.perms.indexOf('email') != -1;
			var res = { status: gotPerm ? 'ok' : 'cancelled' };
			Zoo.FB._sendResult(resultHandler, res);
		}, opt);
	},

	streamPublish: function(resultHandler, params) {
		params.method = 'stream.publish';
		params.display = this._forcePopup ? 'popup' : 'dialog';

		this._onWindowBlock = function() {
			this._sendResult(resultHandler, { status: 'blocked' });
		};
		FB.ui(params, function(response) {
			Zoo.FB._onWindowBlock = null;
			var res = { status: response && response.post_id ? 'ok' : 'cancelled' };
			Zoo.FB._sendResult(resultHandler, res);
		});
	},

	shareLink: function(resultHandler, url) {
		var params = {
			method: 'stream.share',
			display: this._forcePopup ? 'popup' : 'dialog',
			u: url
		};
		this._onWindowBlock = function() {
			this._sendResult(resultHandler, { status: 'blocked' });
		};
		FB.ui(params, function(response) {
			Zoo.FB._onWindowBlock = null;
			var res = { status: 'ok' };
			Zoo.FB._sendResult(resultHandler, res);
		});
	},

	inviteFriends: function() {
		window.open('/fbcanvas?rm=invite', 'invite', 'menubar=0,location=0,status=0,scrollbars=1,width=780,height=580');
	},

	_sendResult: function(handler, res) {
		if(handler) {
			var swf = document.getElementById('zoo_swf');
			swf[handler](res);
		}
	}
};

Zoo.Util = window.Zoo.Util || {
	// install FireBug to enjoy this
	log: function() {
		if(window.console) {
			window.console.log.apply(window.console, arguments);
		}
	},

	openWindow: function(url, options, name) {
		if(!name) name = "_blank";
		return window.open(url, name, options);
	}
};

Zoo.Storage = window.Zoo.Storage || {
	get: function(key) {
		return jaaulde.utils.cookies.get(key);
	},

	set: function(key, value) {
		jaaulde.utils.cookies.set(key, value, { expiresAt: new Date(2020, 1, 1) });
	}
};

Zoo.Analytics = window.Zoo.Analytics || {
	init: function(options) {
		window._gaq = window._gaq || [];
		_gaq.push(['_setAccount', options.account]);
		_gaq.push(['_setDomainName', '.zoo.gr']);
		_gaq.push(['_trackPageview']);

		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

		Zoo.Util.log('Zoo.Analytics.init', options);
	},

	trackPageview: function(url) {
		_gaq.push(['_trackPageview', url]);

		Zoo.Util.log('Zoo.Analytics.trackPageview', url);
	}
}

// we wrap window.open to detect if a window is blocked
window._fb_open = window.open;
window.open = Zoo.FB._window_open;

// for compatibility we have a top-level openWindow
window.openWindow = Zoo.Util.openWindow;


/*** embed libraries to avoid having too many .js files ***/
/* json2.js 
 * 2008-01-17
 * Public Domain
 * No warranty expressed or implied. Use at your own risk.
 * See http://www.JSON.org/js.html
*/
if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();}
/**
 *
 * Copyright (c) 2005 - 2010, James Auldridge
 * All rights reserved.
 *
 * Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
 *  http://code.google.com/p/cookies/wiki/License
 *
 */
var jaaulde=window.jaaulde||{};jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function(){var resolveOptions,assembleOptionsString,parseCookies,constructor,defaultOptions={expiresAt:null,path:'/',domain:null,secure:false};resolveOptions=function(options){var returnValue,expireDate;if(typeof options!=='object'||options===null){returnValue=defaultOptions;}else
{returnValue={expiresAt:defaultOptions.expiresAt,path:defaultOptions.path,domain:defaultOptions.domain,secure:defaultOptions.secure};if(typeof options.expiresAt==='object'&&options.expiresAt instanceof Date){returnValue.expiresAt=options.expiresAt;}else if(typeof options.hoursToLive==='number'&&options.hoursToLive!==0){expireDate=new Date();expireDate.setTime(expireDate.getTime()+(options.hoursToLive*60*60*1000));returnValue.expiresAt=expireDate;}if(typeof options.path==='string'&&options.path!==''){returnValue.path=options.path;}if(typeof options.domain==='string'&&options.domain!==''){returnValue.domain=options.domain;}if(options.secure===true){returnValue.secure=options.secure;}}return returnValue;};assembleOptionsString=function(options){options=resolveOptions(options);return((typeof options.expiresAt==='object'&&options.expiresAt instanceof Date?'; expires='+options.expiresAt.toGMTString():'')+'; path='+options.path+(typeof options.domain==='string'?'; domain='+options.domain:'')+(options.secure===true?'; secure':''));};parseCookies=function(){var cookies={},i,pair,name,value,separated=document.cookie.split(';'),unparsedValue;for(i=0;i<separated.length;i=i+1){pair=separated[i].split('=');name=pair[0].replace(/^\s*/,'').replace(/\s*$/,'');try
{value=decodeURIComponent(pair[1]);}catch(e1){value=pair[1];}if(typeof JSON==='object'&&JSON!==null&&typeof JSON.parse==='function'){try
{unparsedValue=value;value=JSON.parse(value);}catch(e2){value=unparsedValue;}}cookies[name]=value;}return cookies;};constructor=function(){};constructor.prototype.get=function(cookieName){var returnValue,item,cookies=parseCookies();if(typeof cookieName==='string'){returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null;}else if(typeof cookieName==='object'&&cookieName!==null){returnValue={};for(item in cookieName){if(typeof cookies[cookieName[item]]!=='undefined'){returnValue[cookieName[item]]=cookies[cookieName[item]];}else
{returnValue[cookieName[item]]=null;}}}else
{returnValue=cookies;}return returnValue;};constructor.prototype.filter=function(cookieNameRegExp){var cookieName,returnValue={},cookies=parseCookies();if(typeof cookieNameRegExp==='string'){cookieNameRegExp=new RegExp(cookieNameRegExp);}for(cookieName in cookies){if(cookieName.match(cookieNameRegExp)){returnValue[cookieName]=cookies[cookieName];}}return returnValue;};constructor.prototype.set=function(cookieName,value,options){if(typeof options!=='object'||options===null){options={};}if(typeof value==='undefined'||value===null){value='';options.hoursToLive=-8760;}else if(typeof value!=='string'){if(typeof JSON==='object'&&JSON!==null&&typeof JSON.stringify==='function'){value=JSON.stringify(value);}else
{throw new Error('cookies.set() received non-string value and could not serialize.');}}var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString;};constructor.prototype.del=function(cookieName,options){var allCookies={},name;if(typeof options!=='object'||options===null){options={};}if(typeof cookieName==='boolean'&&cookieName===true){allCookies=this.get();}else if(typeof cookieName==='string'){allCookies[cookieName]=true;}for(name in allCookies){if(typeof name==='string'&&name!==''){this.set(name,null,options);}}};constructor.prototype.test=function(){var returnValue=false,testName='cT',testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue){this.del(testName);returnValue=true;}return returnValue;};constructor.prototype.setOptions=function(options){if(typeof options!=='object'){options=null;}defaultOptions=resolveOptions(options);};return new constructor();})();(function(){if(window.jQuery){(function($){$.cookies=jaaulde.utils.cookies;var extensions={cookify:function(options){return this.each(function(){var i,nameAttrs=['name','id'],name,$this=$(this),value;for(i in nameAttrs){if(!isNaN(i)){name=$this.attr(nameAttrs[i]);if(typeof name==='string'&&name!==''){if($this.is(':checkbox, :radio')){if($this.attr('checked')){value=$this.val();}}else if($this.is(':input')){value=$this.val();}else
{value=$this.html();}if(typeof value!=='string'||value===''){value=null;}$.cookies.set(name,value,options);break;}}}});},cookieFill:function(){return this.each(function(){var n,getN,nameAttrs=['name','id'],name,$this=$(this),value;getN=function(){n=nameAttrs.pop();return!!n;};while(getN()){name=$this.attr(n);if(typeof name==='string'&&name!==''){value=$.cookies.get(name);if(value!==null){if($this.is(':checkbox, :radio')){if($this.val()===value){$this.attr('checked','checked');}else
{$this.removeAttr('checked');}}else if($this.is(':input')){$this.val(value);}else
{$this.html(value);}}break;}}});},cookieBind:function(options){return this.each(function(){var $this=$(this);$this.cookieFill().change(function(){$this.cookify(options);});});}};$.each(extensions,function(i){$.fn[i]=this;});})(window.jQuery);}})();
