/*
	Copyright 2007 urSpin <http://urspin.com>

	urSpin Webtop JS
	
	Requires Mootools 1.1
		Core:
			*
		Class:
			*
		Native:
			*
		Element:
			Element.Selectors
			Element.Filters
			Element.Event
			Element.Dimensions
		Window:
			Window.DomReady
			Window.Size
		Effects:
			Fx.Base
			Fx.CSS
			Fx.Styles
			Fx.Elements
		Drag:
			Drag.Base
			Drag.Move
		Remote:
			XHR
			Ajax
			Assets
			Json
*/

/*
Section: urspin.js
*/


/*
	Class: URSPIN
	
	Global URSPIN object
*/
var URSPIN = {
	domReady: false,
	dataReady: false,
	localeDataReady: false,
	imagesReady: false,
	googleReady: false,

	// x: {
	// 	'API_KEY':''
	// },


	/*
		Method: startWhenReady
	*/
	startWhenReady: function () {
		// use domready event to wait until page is loaded 
		// domready fires when all html, css, and scripts are loaded
		// (i.e. it doesn't wait for images or other media)
		window.addEvent('domready', this.onDOMReady.bind(this));

		if (google) {
			google.load('feeds', '1');
			google.load('search', '1');
			google.setOnLoadCallback(URSPIN.onGoogleReady.bind(URSPIN));
		} else {
			this.googleReady = true;
		}
	},
	
	// imageSources: [
	// 	'btn_bg_c.png',
	// 	'btn_bg_lr.png',
	// 	'btn_icn_plus.png',
	// 	'btn_icn_dwn_arr.png',
	// 	'icon_plus.png',
	// 	
	// 	'menu_bg_lr_tb.png',
	// 	'menu_bg_c_tb.png',
	// 	'menu_bg_r.png',
	// 
	// 	'add_stuff/bg_c.png',
	// 	'add_stuff/bg_corners.png',
	// 	'add_stuff/bg_lr.png',
	// 
	// 	'add_stuff/dir/bg_black_c.png',
	// 	'add_stuff/dir/bg_green_c.png',
	// 	'add_stuff/dir/bg_grey_c.png',
	// 	'add_stuff/dir/bg_orange_c.png',
	// 	'add_stuff/dir/btn_back.png',
	// 	'add_stuff/dir/select_bg_lr.png',
	// 	'add_stuff/dir/select_bg_c.png',
	// 	'add_stuff/dir/search_bg_c.png',
	// 	'add_stuff/dir/search_bg_lr.png',
	// 
	// 	'hdr/cmd_bar_right_bg.png',
	// 	'hdr/logo.png',
	// 
	// 	'mod/title_bar_bg_blue_c.png',
	// 	'mod/title_bar_bg_blue_lr.png',
	// 	'mod/title_bar_bg_green_c.png',
	// 	'mod/title_bar_bg_green_lr.png',
	// 	'mod/title_bar_bg_light_blue_c.png',
	// 	'mod/title_bar_bg_light_blue_lr.png',
	// 	'mod/title_bar_bg_purple_c.png',
	// 	'mod/title_bar_bg_purple_lr.png',
	// 	'mod/title_bar_bg_orange_c.png',
	// 	'mod/title_bar_bg_orange_lr.png',
	// 	'mod/title_bar_bg_red_c.png',
	// 	'mod/title_bar_bg_red_lr.png',
	// 	'mod/title_bar_btns.png',
	// 
	// 	'mod/con_bg_r.png',
	// 	'mod/ftr_bg_lr.png',
	// 	'mod/ftr_bg_c.png',
	// 
	// 
	// 	'tab_bar/tab_bar_shadow.png',
	// 	'tab_bar/tab_bg.png'
	// ],
	// 
	// imagePath: 'a/images/',

	/*
		Method: onDOMReady
	*/
	onDOMReady: function (e) {
		// for (var i = 0; i < this.imageSources.length; i++) {
		// 	this.imageSources[i] = this.imagePath + this.imageSources[i];
		// }
		// 
		// var loader = Asset.images(this.imageSources, {
		// 	'onProgress': this.onImageProgress.bind(this),
		// 	'onComplete': this.onImageReady.bind(this)
		// });
		this.imagesReady = true;

		// AJAX request for user data
		var date = new Date();
		var params = {'cmd':'get','mod':60 * date.getHours() + date.getMinutes()};
		new XHR({'onSuccess': this.onInitialDataReady.bind(this)}).send('services/wt/user/', Object.toQueryString(params));

		this.domReady = true;
		this.onReady();
	},
	
	
	onGoogleReady: function () {
		this.googleReady = true;
		this.onReady();
	},
	
	
	onInitError: function (e) {
		console.dir(e);
	},
	
	/*
		Method: onDataReady
	*/
	onInitialDataReady: function (text, xml) {
		this.data = {};
		try {
			this.data = Json.evaluate(text);
			console.dir({'initial data':this.data});
		} catch (e) {
			this.onInitError({'exception':e});
			return;
		}
		
		if (this.data.error) {
			this.onInitError(this.data.error);
			return;
		}

		this.$localeLoaded = function (locale) {
			this.localeDataReady = true;
			this.$localeLoaded = null;
			URSPIN.l10n.removeEvent('localechange', this.$localeLoaded);

			this.onReady();
			// console.dir({'localeStrings':URSPIN.l10n.localeStrings});


			// update text and href of links
			var ids = [
				['page.hdr.signin', 'User/SignIn', 1],
				['page.hdr.signout', 1],
				['page.hdr.signup', 'User/SignUp', 1],
				// ['page.hdr.startover', 'User/StartOver'],
				['page.hdr.getstart', 'Support/GettingStarted'],
				['page.hdr.settings', 'User/Settings', 1],
				// ['page.hdr.help', 'Support/'],
				// ['page.hdr.newfeatures', 'Support/NewFeatures'],

				['page.ftr.tos', 'Support/TermsOfService'],
				['page.ftr.pp', 'Support/PrivacyPolicy'],
				['page.ftr.feedback', 'Support/Feedback', 1],
				['page.ftr.contactus', 'Support/ContactUs', 1],
				['page.ftr.aboutus', 'AboutUs']
			];

			var path = window.location.pathname;
			while (path.length > 0 && path.charAt(path.length - 1) != '/') {
				path = path.substring(0, path.length - 1);
			}
			var httpURL = '';
			var httpsURL = httpURL; //'https://' + window.location.host + path;

			for (var i = 0; i < ids.length; i++) {
				var el = $(ids[i][0].replace(/\./g,'-'));
				if (el) {
					el.setText(URSPIN.l10n.getString(['ui.', ids[i][0]].join('')));
					if (ids[i][1]) {
						
						el.setProperty('href', [ids[i][2] ? httpsURL : httpURL, 'Pages/', langTag, '/', ids[i][1]].join(''));
					}
				} else {
					console.warn(['l10n: element not found: ', ids[i][0].replace(/\./g,'-')].join(''));
				}
			}
			
			$(document).getElements('.hw-l10n').each(function (el) {
				el.removeClass('hw-l10n');
			});

			$('hdr-search-type-w').getElements('span').each(function (el) {
				var st = el.getProperty('stype');
				if (st) {
					el.setText(URSPIN.l10n.getString(['ui.hdr.search.', st].join('')));
				}
			});
		}.bind(this);

		var langTag = this.data.user.profile[0];

		URSPIN.l10n.addEvent('localechange', this.$localeLoaded);
		URSPIN.l10n.setLocale(langTag);

		this.dataReady = true;		
		this.onReady();
	},
	
	/*
		Method: onReady
	*/
	onReady: function () {
		if (this.domReady && this.localeDataReady && this.dataReady && this.imagesReady && this.googleReady) {
			// get webtop object
			var userData = {
				'langTag':this.data.user.profile[0],
				'openedUserTabID':this.data.user.profile[1],
				'username':this.data.user.profile[2],
				'taborder':this.data.user.profile[3],
				'tabs':this.data.user['tabs'],
				'theme':this.data.user.profile[4]
			};

			this.webtop = new URSPIN.Webtop(userData);

			$('webtop-loading-throbber').remove();

			$(document).getElements('.hw-webtop').each(function (el) {
				el.removeClass('hw-webtop');
			});
			
			
			
			// this.fireEvent('ready');
		}
	},
	
	getWebtop: function () {return this.webtop;},
	
	eatEvent: function (e) {
		e.stopPropagation();
	}.bindWithEvent()

};
URSPIN.startWhenReady();


/*
	Class: URSPIN.Locale
		Singleton
*/
URSPIN.l10n = new Class({

	defaultLocale:'en',
	defaultLocaleLoaded:false,
	currentLocale:null,
	localeStrings:{},


	setLocale: function (locale, options) {
		locale = locale || this.defaultLocale;
			// || navigator.userLanguage
			// || navigator.browserLanguage
			// || navigator.systemLanguage
			// || navigator.language;
		

		if (!this.currentLocale || this.currentLocale != locale || options.forceReload) {
			this.defaultLocaleLoaded = false,
			this.load(locale);
		}
	},
	
	getLocale: function () {return this.currentLocale;},

	getString: function (key) {
		key = key.trim();
		if (key.test('^ui\.') && this.localeStrings[key]) {
			return this.localeStrings[key];
		} else {
			console.warn(['No locale-string found for key: ', key].join(''));
			return '';
		}
	},
	
	onLocaleChange: function (newLocale) {
		// console.dir({'URSPIN.l10n':this});
		this.currentLocale = newLocale;
		this.fireEvent('localechange', [newLocale]);
	},

	load: function (locale, options) {
		locale = locale || this.defaultLocale;
		options = options || {};

		if (!this.defaultLocaleLoaded) {
			// AJAX request for default locale data.
			// when requests completes, load() is called again
			new XHR({
				'method':'get',
				'onSuccess':function (text) {
					this.defaultLocaleLoaded = true;
					// console.info('URSPIN.l10n: loaded default:', this.defaultLocale);
					try {
						var localeObj = Json.evaluate(text);
						$extend(this.localeStrings, localeObj.strings);
					} catch (err) {
						// console.error(err);
					}

					this.currentLocale = this.defaultLocale;
					this.load(locale, options);
				}.bind(this)
			}).send(['services/wt/l10n/', this.defaultLocale, '.json'].join(''));
		} else {

			var onComplete = function (text) {this.onLocaleLoad(text, locale);}.bind(this);

			if (this.defaultLocale != locale){
				// AJAX request for locale data.
				new XHR({
					'method':'get',
					'onSuccess':this.onLocaleLoad.bindAsEventListener(this, [locale]),
					'onFailure':this.onLocaleLoadFailure.bindAsEventListener(this, [locale])
				}).send(['services/wt/l10n/', locale, '.json'].join(''));
			} else {
				this.onLocaleLoad(null, locale);
			}
		}
	},

	onLocaleLoadFailure: function (xhr, attemptedLocale) {
		// it's okay. default locale should already be loaded
		// console.warn('onLocaleLoadFailure: could not load locale: ' + attemptedLocale);
		this.fireEvent('localechange', [this.defaultLocale]);
	},

	onLocaleLoad: function (text, newLocale) {
		if (text && text.length > 0) {
			// console.info('URSPIN.l10n: loaded:', newLocale);
			try {
				var localeObj = Json.evaluate(text);
				$extend(this.localeStrings, localeObj.strings);
			} catch (err) {
				// console.error('Json.evaluate', err);
			}
		}
		this.onLocaleChange(newLocale);
	}
});
URSPIN.l10n.implement(new Events);
// URSPIN.l10n is a singleton, so instantiate now, and overwrite "class" definition 
URSPIN.l10n = new URSPIN.l10n();


/*
	Class: URSPIN.Icon
*/
URSPIN.Icon = new Class({
	src:'default_icon_source',
	altText:'',
	
	initialize: function (iconData) {
		if (iconData) {
			this.src = iconData.imgSrc || this.src;
		}
	},

	setSource: function (src) {
		this.src = src;
		if (this.el) {
			this.el.src = this.src;
		}
	},
	
	getImageElement: function () {
		this.el = this.el || new Element('img', {'src':this.src,'alt':this.altText});
		return this.el;
	},
	
	clicked: function (e) {}

});

