
// jquery.jsonp 2.1.4 (c)2010 Julian Aubourg | MIT License
// http://code.google.com/p/jquery-jsonp/
(function(e,b){function d(){}function t(C){c=[C]}function m(C){f.insertBefore(C,f.firstChild)}function l(E,C,D){return E&&E.apply(C.context||C,D)}function k(C){return/\?/.test(C)?"&":"?"}var n="async",s="charset",q="",A="error",r="_jqjsp",w="on",o=w+"click",p=w+A,a=w+"load",i=w+"readystatechange",z="removeChild",g="<script/>",v="success",y="timeout",x=e.browser,f=e("head")[0]||document.documentElement,u={},j=0,c,h={callback:r,url:location.href};function B(C){C=e.extend({},h,C);var Q=C.complete,E=C.dataFilter,M=C.callbackParameter,R=C.callback,G=C.cache,J=C.pageCache,I=C.charset,D=C.url,L=C.data,P=C.timeout,O,K=0,H=d;C.abort=function(){!K++&&H()};if(l(C.beforeSend,C,[C])===false||K){return C}D=D||q;L=L?((typeof L)=="string"?L:e.param(L,C.traditional)):q;D+=L?(k(D)+L):q;M&&(D+=k(D)+encodeURIComponent(M)+"=?");!G&&!J&&(D+=k(D)+"_"+(new Date()).getTime()+"=");D=D.replace(/=\?(&|$)/,"="+R+"$1");function N(S){!K++&&b(function(){H();J&&(u[D]={s:[S]});E&&(S=E.apply(C,[S]));l(C.success,C,[S,v]);l(Q,C,[C,v])},0)}function F(S){!K++&&b(function(){H();J&&S!=y&&(u[D]=S);l(C.error,C,[C,S]);l(Q,C,[C,S])},0)}J&&(O=u[D])?(O.s?N(O.s[0]):F(O)):b(function(T,S,U){if(!K){U=P>0&&b(function(){F(y)},P);H=function(){U&&clearTimeout(U);T[i]=T[o]=T[a]=T[p]=null;f[z](T);S&&f[z](S)};window[R]=t;T=e(g)[0];T.id=r+j++;if(I){T[s]=I}function V(W){(T[o]||d)();W=c;c=undefined;W?N(W[0]):F(A)}if(x.msie){T.event=o;T.htmlFor=T.id;T[i]=function(){/loaded|complete/.test(T.readyState)&&V()}}else{T[p]=T[a]=V;x.opera?((S=e(g)[0]).text="jQuery('#"+T.id+"')[0]."+p+"()"):T[n]=n}T.src=D;m(T);S&&m(S)}},0);return C}B.setup=function(C){e.extend(h,C)};e.jsonp=B})(jQuery,setTimeout);

$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};

function log(){
	try {
		console.log.apply(this,arguments);
	}
	catch(e){}
}
/* 
	requires:
		jQuery 1.3.2+
		$.toJSON jQuery plugin
 */
 

var Overlay = {
	show: function(){
		if (!this.overlay) {
			this.overlay = $('<div class="overlay loading"></div>').appendTo('body');
		}
		var w = $(window);
		var top = w.scrollTop();
		var height = w.height();
		var pos_top = top + (height/2) - 10;

		this.overlay.css({'background-position': 'center '+pos_top+'px'});
		this.overlay.show();
		this._fixHeight();
	},
	hide: function(){
		if (!this.overlay) {
			this.overlay = $('<div class="overlay loading"></div>').appendTo('body');
		}
		this.overlay.hide();
	},
	_fixHeight: function(){
		var h = $(document).height();
		$(".overlay").height(h);
	}
};
var Modal = {
	visible: false,
	show_error: function(msg){
		var errorDiv = this.errorDiv ? this.errorDiv : $(".bd > .error", this.wrapper);
		
		if (!errorDiv || !errorDiv.length) { 
			 errorDiv = $('<div class="error"></div>').prependTo($(".bd", this.wrapper));

			 this.errorDiv = errorDiv;
		}
		if (this.type == 'wizard') {
			errorDiv.html('<p>'+msg+'</p>').slideDown();
		}
		else { 
			errorDiv.html('<p>'+msg+'</p>').show();
		}
		this.fixIE();
	}, 
	
	clear_error: function(){
		if (this.errorDiv) {
			this.errorDiv.html('').hide();
		}
	},

	show_json_error: function(json){
		var errors = json.HEAD.errors;
		var e = [];
		$.each(errors, function(i, val){
			e.push(val.message);
		});
		this.show_error(e.join('<br/>'));
	},
	
	fixIE: function(){		
		$(".ft", this.modal).css({position:'absolute'}).css({position:'static'})
	},
	
	overlay: null,
	_fixHeight: function(){
		var h = $(document).height();
		$(".overlay", this.modal).height(h);
	},

	fetch: function(settings){
		this.settings = settings;
		if (!settings.name && !settings.url) { throw 'no name or url supplied'; return false; }
		var self = this;
		Overlay.show(); 
		self.type = settings.type ? settings.type : "billboard";
		
		if (settings.name) {
			var req = {
				HEAD: {
					widget_name: settings.widget_name || 'pages',
					action: 'view',
					output_format: 'posh'
				},
				BODY: {
					name: settings.name
				}
			};
		}
		var data = {
			soapjr: $.toJSON(req)
		};
		$.ajax({
			type: 'post',
			url: '/home',
			data: data,
			dataType: 'html',
			success: function(html){ 
				Overlay.hide();
				self.show({
					hd: settings.title,
					bd: html,
					className: settings.className,
					onSubmit: settings.onSubmit,
					onClose: settings.onClose
				});
				$(".tooltip", self.modal).tooltip();
				if (settings.callback && typeof(settings.callback) == 'function') {
					settings.callback();
				}
			},
			error: function(){
				self.show_error('Network error')
			}
		});
	},
	show: function(settings){
		this.settings = settings;
		var types = {billboard: '#billboard', wizard: '#wizard'};
		this.type = settings.type ? settings.type : ( this.type ? this.type : "billboard");
		if (!this.modal) {
			this.modal = $("#modal");
		}
		// hide other types
		
		for (var i in types){
			if (this.type == i){ this.wrapper = $(types[i]).show(); }
			else { $(types[i]).hide(); }
		}
		this.errorDiv = null;
		
		$("*", this.wrapper).unbind();
		this.wrapper.removeAttr('style');
		var c = $(".bd", this.wrapper).html(settings.bd);

		if (c.find("#foot_content").length) { 
			$(".ft", this.wrapper).html($("#foot_content").show());
		}
		else if(settings.ft) {
			$(".ft", this.wrapper).html(settings.ft);
		}
		else {
			$(".ft", this.wrapper).html('');
		}
		
		if (this.type == 'billboard') {
			$(".hd h3", this.wrapper).text(settings.hd);
		}
		else if(c.find("#wizard_menu").length) {
			$(".menu", this.wrapper).html(c.find("#wizard_menu")).append('<a class="close" href="javascript:void(0)" onclick="Modal.hide()"></a>')
		}
		else {
			$(".menu", this.wrapper).html('<a class="close" href="javascript:void(0)" onclick="Modal.hide()"></a>');
		}

		this.wrapper.attr({"class": (settings.className? settings.className+" " : '')+this.type});
		this._fixHeight();

		// position in center of viewport if possible
		this.modal.css({visibility: 'hidden'}).show();

		if ($.fn.prompt) {
			$(".prompt", this.modal).prompt();
		}
		if ($.fn.tabbed) {
			$(".tabbed", this.modal).tabbed();
		}
		if ($.fn.tooltip) {
			$(".tooltip", this.modal).tooltip();
		}
		if ($.fn.prettyCheckboxes) {
			$('input[type=checkbox], input[type=radio]', this.modal).prettyCheckboxes($.checkboxDefaults);
		}

		// trigger submit handler on <enter>
		$("input[type=text], input[type=password]", this.modal).bind('keyup', function(e){ 
			if (e.keyCode == 13){
				e.preventDefault();
				e.stopPropagation();
				if (settings.onSubmit && typeof(settings.onSubmit) == 'function') {
					$("input[type=text], input[type=password]", this.modal).blur(); // to avoid double submit
					settings.onSubmit(this);
				}
				return false;				
			}
		});

		//var offset = $(window).scrollTop() + 0.5*parseInt($(window).height(),10);
		//var top = offset - (0.5*parseInt(this.wrapper.height()));

		//this.wrapper.css('top', top > 0 ? top : 10);
		this.modal.css({visibility: 'visible'});
		$(":input", this.modal).not("[readonly], [disabled]").first().focus();


		//Cufon.replace('#modal .vagbold, #modal .vag, #modal .btn_blue, #modal .btn', { fontFamily: 'Vag', hover: true });
		
		if (settings.callback && typeof(settings.callback) == 'function') {
			settings.callback();
		}
		this.visible = true;

	},
	hide: function(confirmed){
		if (!this.visible) { return; }
		var settings = this.settings;
		if (!this.modal) {
			this.modal = $("#modal");
		}
		if (this.type == 'wizard') {
			$(".menu", this.wrapper).html('<a class="close" href="javascript:void(0)" onclick="Modal.hide()"></a>');
		}
		$(".bd", this.wrapper).html('');
		$("*", Modal.modal).unbind();
		if (confirmed) {
			this.modal.hide();
		}
		else if (settings && settings.onClose && typeof(settings.onClose) == 'function') {
			if (!settings.onClose()){
				return false;
			}
		}		
		this.modal.hide();
		this.visible = false;
	}
};

var Service = {
	call: function(opt){
		var HEAD = $.extend({
			widget_name: opt.widget_name,
			action: opt.action,
//			pretty: 1,
			output_format: opt.output_format || 'soapjr'
		}, opt.HEAD);
		
		var BODY = opt.BODY || {};
		var self = this;
		var callback = opt.callback || 'Overlay.hide';
		var errorCallback = opt.errorCallback ? opt.errorCallback : $.noop;
		Overlay.show();
		
		return $.jsonp({
			url: DOMAIN+'/home?soapjr='+encodeURIComponent($.toJSON({HEAD:HEAD, BODY:BODY})), 
			type: 'get',
			cache: opt.cache,
			timeout: 30000,
			dataType: 'jsonp',
			callbackParameter: 'callback',

			success: function(data, textStatus){ 
				Overlay.hide(); 
				if (opt.onSuccess) {
					opt.onSuccess(data)
				}
				else {
					var temp = callback.split('.');
					var f = window;
					var o;
					$.each(temp, function(a, part){
						if (f[part]) { 
							f = f[part];
							if (a == 0) { 
								o = f;
							}
						}
					});
					if (typeof(f) == 'function'){
						f.call(o, data);
					}
				}
				
			},
			error: function(xOptions, textStatus){ 
				log('A network error occurred. Please check your connectivity and try again', xOptions, textStatus)
				Overlay.hide(); 
				errorCallback();
			}
		});
	}
};

if (typeof Object.size !== 'function') {
	Object.size = function (o) {
		var size = 0, key;
    for (key in o) {
        if (o.hasOwnProperty(key)) size++;
    }
    return size;
	};
}

var Categories = {
	'For Kids': {
		color: 'green',
		name: 'for kids',
		text_color: 'dark'
	},
	'Workshops': {
		color: 'red',
		name: 'workshops',
		text_color: 'white'
	},
	'Tours': {
		color: 'sand',
		name: 'tours',
		text_color: 'white'
	},
	'Talks': {
		color: 'pumpkin',
		name: 'talks',
		text_color: 'white'
	},
	'Markets': {
		color: 'teal',
		name: 'markets',
		text_color: 'white'
	},
	'For Students': {
		color: 'salmon',
		name: 'for students',
		text_color: 'white'
	},
	'Exhibitions': {
		color: 'grey',
		name: 'Exhibitions',
		text_color: 'white'
	},
	'Events': {
		color: 'blue',
		name: 'events',
		text_color: 'white'
	},
	'default': {
		color: 'grey',
		name: 'none',
		text_color: 'white'
	}
};


var App = {
	search_ready: false,
	keywordsReady: false,
	eventsReady: false,
	checkSearchReady: function(){ 
		if (this.keywordsReady && this.eventsReady) { 
			$(window).trigger('search_ready');
		}
	},
	sortPH: function(events){
	
		var ph = [];
		var rest = [];
		$.each(events, function(i, a){
			if (a.location && a.location.name && a.location.name.toLowerCase() == 'powerhouse museum') { 
				ph.push(a);
			}
			else {
				rest.push(a);
			}
		});
		return $.merge(ph, rest);
	},
	getCategoryForEvent: function(event){
		if (!event || !event.categories || !event.categories.length) {
			return '';
		}
		var c = 'default';
		$.each(event.categories, function(i, cat){
			if (Categories[cat]) {
				c = cat;
			}
		});
		return c;
	},
	setupKeywords: function(json){
		try {
			
			this._keywords = json.BODY
			this.prepareKeywords();
			this.keywordsReady = true;
			this.checkSearchReady();
		}
		catch(e){}
	},
	setupFeatured: function(json){
		try {
			this.featured = json.BODY
			this.prepareLocations()
		}
		catch(e){}	
	},
	setupLocations: function(json){
		try {
			this._locations = json.BODY;
			this.prepareLocations();
		}
		catch(e){}	
	},
	setupEvents: function(json){ 
		try {
			this._events = json.BODY;
			this.prepareEvents(); 
			this.eventsReady = true;
			this.checkSearchReady(); 
			$(window).trigger('search_location_ready');
		}
		catch(e){}
	},
	// temp
	tempSetup: function(){
		this.prepareLocations();
		this.prepareKeywords();
		this.prepareEvents();
		this.ready = true;
	},
	prepareLocations: function(){
		var k = {};
		$.each(this._locations, function(i, location){
			k[location.id] = location
		});
		this.locations = k;
	},
	prepareKeywords: function(){
		var k = {};
		$.each(this._keywords, function(i, keyword){
			keyword.word = keyword.word + '';
			
			var w = keyword.word.toLowerCase();

			if (!k['_'+w]) {
				k['_'+w] = []
			}
			try {
				k['_'+w].push(keyword.id);
			}
			catch(e){}
		});
		this.keywords = k;
		
	},
	prepareEvents: function(){
		var e = {};
		$.each(this._events, function(i, event){
			e[event.id] = event;
		});
		this.events = e;
	}
	
};

var Map = {
	show: function(location_id) {
		var loc = App.locations[location_id];
		if (loc && loc.geocode && loc.geocode.latitude && loc.geocode.longitude) {
			Modal.show({
				hd: loc.name,
				bd: '<div id="map" class="map"></div>'
			});
			var myLatlng = new google.maps.LatLng(loc.geocode.latitude, loc.geocode.longitude);
		    var myOptions = {
		      zoom: 16,
		      center: myLatlng,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    }
		    var map = new google.maps.Map(document.getElementById("map"), myOptions);
		    
		    var marker = new google.maps.Marker({
		        position: myLatlng, 
		        map: map,
		        title: loc.name
		    }); 
		}
	}
};
var Search = {
	loadLocation: function(){},
	load: function(keywords){		
		var results = {};
		var items = [];
		var temp = keywords.split(' ');
		$.each(temp, function(i, keyword){
			keyword = (keyword+'').toLowerCase();
			var event_ids = App.keywords['_'+keyword];
			
			if (event_ids && event_ids.length) {
				$.each(event_ids, function(i, id){
					if (App.events[id] && !results[id]) {
						results[id] = App.events[id];
						items.push(App.events[id]);
					}
					else if (!App.events[id]) {
						try { console.log('no data '+id); } catch(e) {}
					}
				});

			}
		});
		
		if (items.length){
			if (this.sortByName && typeof(this.sortByName) == 'function') {
				this._event_list = items;
				this.sortByName();
			}
			else {
				this.renderResults(items);
			}
		}
		else {
			this.renderNoResults();
		}
		
	},
	renderNoResults: function(){
		$("#search_results").html('<div class="box"><h2 class="event_title event_title_plain">There are no events that match your search criteria.</h2></div>');
	},
	renderResults: function(results){ 
		var html = '';
		results = App.sortPH(results);
		
		$.each(results, function(i, result){ 
			var tags = [];
			if (result.tags) {
				$.each(result.tags, function(i, tag){
					tags.push('<a href="'+tag+'">'+i+'</a>');
				});
			}
			html += '<div id="post-'+result.id+'" class="post"><a href="'+result.permanent_link+'" title="Permalink to event" rel="bookmark"><img class="event_thumbnail" src="'+BASE_URL+'/events/'+result.id+'-pc-thumb.jpg" alt="" /></a><h2 class="event_title"><a href="'+result.permanent_link+'" title="Permalink to event" rel="bookmark">'+result.title+'</a></h2><div class="event_summary">'+result.short_description+'</div><div class="event_tags">'+tags.join(', ')+'</div></div>';
			
		});
		
		$("#search_results").html(html);
	}
};



var Featured = {
	timeouts: {},
	play: function(opts){
		opts = $.extend({
			interval: 5000,
			cnt: '#featured',
			items: 'li'
		}, opts);
		var cnt = $(opts.cnt);
		cnt.each(function(i){
			var c = $(this),
				items = $(opts.items, cnt),
				l = items.length,
				current = l-1;
			items.hide().eq(current).show();
			Featured.timeouts[i] = setInterval(function(){
				var next = current > 0 ? current-1 : l-1
				
				items.eq(next).fadeIn();
				items.eq(current).fadeOut(function(){
					current = next;
				});
			}, opts.interval);
		});
	},
	stop: function(){
		$.each(this.timeouts, function(i, t){
			clearInterval(t);
		})
	}
};
// placeholder test
$(function() {
	jQuery.support.placeholder = false;
	test = document.createElement('input');
	if('placeholder' in test) jQuery.support.placeholder = true;
	$("input").prompt();
});
$.fn.extend({
	prompt: function(){
		// test if supports placeholder attribute
		
		if ($.support.placeholder) { return $(this); }
				
		return this.each(function(){
			var el = $(this);
			var ph = el.attr('placeholder');
					
			if (!el.val()) {
				el.val(ph).addClass('placeholder');
			}
			el.focus(function(e){
				if (this.value == ph) {
					this.value = '';
					el.removeClass('placeholder');
				}
			})
			.blur(function(e){
				if (this.value == ph || this.value === '') {
					this.value = ph;
					el.addClass('placeholder');
				}
			});
		});
	}
});

