/* GLOBAL VARS */
//cfg = {lang:'se', root:'http://dev.bonmagazine.com/', cms:'live/'} DISABLED 2011-09-13

/* GLOBAL CLASSES & FUNCTIONS */
function Lang(text) {
	
	this._ = function ( text ) {
		var lang = $.cookie('lang');
		if(this.languages[lang] != null) {
			if(this.languages[lang][text] != null) {
				return this.languages[lang][text];
			} else {
				console.log('i18n: Text not set: '+lang+':'+text);
				return text;
			}
		} else {
			console.log('i18n: Language not set: '+lang);
			return text;
		}
	}
	
	this.languages = {
		se:{
			previous:'föregående',
			next:'nästa',
			one_film: 'film.',
			films:'filmer.',
			last_updated:'Senast uppdaterad',
			film:'Film',
			film_gallery:'Filmgallerier',
			films_from:'Filmer från',
			galleries:'bildserier.',
			one_gallery:'bildserie.',
			more_from:'mer från',
			image:'Bild',
			close:'Stäng'
		},
		en:{
			previous:'previous',
			next:'next',
			films:'films.',
			one_film: 'film.',
			last_updated:'Last updated',
			film:'Film',
			film_gallery:'Film Gallery',
			films_from:'Films from',
			galleries:'galleries.',
			one_gallery:'gallery.',
			more_from:'more from',
			image:'Photo',
			close:'Close'
		}
		
	};
	return this._(text);	
}

FragmentParser = function () {
	var ret = '/';
	var history = [];
	
	this.set = function (_data, _return) {
		//console.log('input', _data);
		for (var i in _data) {
			if(i.substr(0,1) != '_'){
				ret += i+'='+_data[i]+';';
			}
		}
		ret = ret.slice(0, -1);
		//console.log('output', ret);
		if(_return) {
			return ret;
		} else {
			location.hash = ret;
		}
	}
	
	this.get = function () {
		ret = {};
		var loc = location.hash.toString();
		if($.browser.mozilla){
			// FIX FOR AUTO DECODE URI THAT FIREFOX DOES
			// CHECK FOR QUERY, IF TRUE SEARCH FOR QUERY SECTION AND URIENCODE IT
			loc = loc.split('?');
			if(loc.length > 1) {
				loc = loc[0]+'?'+encodeURIComponent(loc[1]);
			} else {
				loc = loc.toString();
			}
		}
		var arr = loc.slice(2).split(';');
		
		//console.log('FragmentParser::get()', arr);
		for (var i=0; i<arr.length; i++) {
			var keyVal = arr[i].split('=');
			if(keyVal.length == 2) {
				var regex = /^\d$/;
				if(regex.exec(keyVal[1])) {
					keyVal[1] = Number(keyVal[1]);
				}
				ret[keyVal[0]] = keyVal[1];
			}
		}
		ret._input = location.hash.slice(1, -1);
		//console.log('get output', ret);
		return ret;
	}
		
	return this;
}

/* BON CLASS */
Events = {};
Events.Bon = {
	HASH_CHANGE				:'hashchange.BON',
	CLOSE_ALL_WINDOWS		:'closeAllWindows.BON',
	SCROLL_TO_TOP			:'scrollToTop.BON',
}


Bon = function (_data) {
	Bon.prototype._			= function (text) { return Lang(text) };
	Bon.prototype.fragment	= FragmentParser;
	var that				= this;
	this.history			= [];
	this.children			= { gallery:null, article:null };
	this.cfg				= {lang:'se', root:'http://dev.bonmagazine.com/', cms:'live/', debug:false};
	this.data				= _data;
	this.previousScroll		= 0;
	
	this.init = function () {
		console.log('Bon::init()', $.cookie('lang'));
		//console.log($.cookie('lang'));
		//console.log(that.data.meta.lang);
		//console.log(that.data.meta.time);
		// LOAD DATA
		// dev.bonmagazine.com/live/se/data/?video
		//this.setup();
		// SETUP FOR IPAD
		this.cfg.iPad = navigator.userAgent.match(/iPad/i) != null;
		this.cfg.iPhone = navigator.userAgent.match(/iPhone/i) != null;
		if( this.cfg.iPad || this.cfg.iPhone ){
			$('html').addClass('ipad');
		}
		that.setupLandingPage();
		that.setupSkin();
		// SETUP LISTENERS
		$(window).bind(Events.Bon.HASH_CHANGE, that.fragmentController);
		$(window).bind(Events.Bon.SCROLL_TO_TOP, that.scrollToTop);
		//$(window).scroll();
		//$('.read_more_link').click(that.saveScrollPosition);
		this.fragmentController();
		
		//MINIMAGAZINE
		if($('.minimagazine_page').length > 0){
			console.log('Bon::init - minimagazine detected');
			Minimagazine.start();
		}
	}
	
	this.setup =  function () {
		// START SYSTEM
		//this.fragmentController();
		$('.gallery_btn').click(this.startGallery);
		//this.children.gallery = new Bon.Gallery($('.gallery_container'));
	}
	
	this.setupSkin = function () {
		//console.log('Bon::setupSkin()', that.data);
		if($('html').hasClass('ipad')){
			$('#fullpage').css('background', 'url("'+that.data.theme.background_ipad+'") top center fixed');	
		} else {
			$('#fullpage').css('background', 'url("'+that.data.theme.background+'") top center fixed');
		}
		
	}
		
	this.fragmentController = function () {
		frag		= that.fragment().get();
		that.history.push(frag);
		console.log('Bon::fragmentController()', frag);
		if(frag.go == null) {
			that.closeAllWindows();
		} else {
			switch(frag.go){
				case '#':
				case '':
					that.closeAllWindows();
					break;
				case 'videogallery':
				case 'imagegallery':
					//Gallery
					if(that.children.gallery == null){
						that.startGallery(frag.go);
					} else {
						console.log('BON::updategallery', that.children.gallery);
						if(that.children.gallery.cfg.type == 'image' && frag.go == 'imagegallery'){
							$(window).trigger('update.GALLERY');
						} else if (that.children.gallery.cfg.type == 'video' && frag.go == 'videogallery') {
							$(window).trigger('update.GALLERY');
						} else {
							that.startGallery(frag.go);
						}
					}
					$(window).trigger('closeSection.ARTICLE');
					break;
				case 'article':
					//Article
					if(that.children.article == null ){
						that.startArticle();
					} else {
						console.log('BON::fragmentController -> article update', that.children.article);
						$(window).trigger('update.ARTICLE');
					}
					$(window).trigger('closeSection.GALLERY');
					break;
				default:
					break;
			}
		}
	}
	
	that.closeAllWindows = function () {
		console.log('BON::CLOSE_ALL_WINDOWS');
		$(window).trigger(Events.Bon.CLOSE_ALL_WINDOWS);
		that.children.gallery = null;
		that.children.article = null;
		that.restoreScrollPosition();
	}
	
	this.updateFragmentToLatestContent = function () {
		console.log('UFTLC', that.data.video_gallery.collections[0].id, that.data.video_gallery.collections[0].contents[0].id, that.data.video_gallery );
		location.hash = this.fragment().set({go:'videogallery', gid:that.data.video_gallery.collections[0].id, vid:that.data.video_gallery.collections[0].contents[0].id}, true);
		//this.startGallery();
	}
	
	this.previousState = function () {
		if(that.history.length >= 2 ){
			return that.history[that.history.length-2];
		} else {
			return false;
		}
	}
	
	this.startGallery = function (type) {
		$(window).bind('closeSection.GALLERY', that.closeGallery);
		var data = '';
		params = { lang:that.data.meta.lang, from:that.previousState() };
		if(type == 'videogallery'){
			params.type = 'video';
			data =  that.data.video_gallery;
		} else if (type == 'imagegallery') {
			params.type = 'image';
			data =  that.data.image_gallery;
		}
		console.log('Bon::startGallery()', params);
		//debugger;
		that.saveScrollPosition();
		this.children.gallery = new Gallery($('.gallery_container'), params, data);		
	}
	
	this.closeGallery = function () {
		console.log('Bon::closeGallery()');
		that.children.gallery = null;
	}
	
	this.startArticle = function () {
		//$(window).unbind('.ARTICLE');
		that.saveScrollPosition();
		$(window).bind('closeSection.ARTICLE', that.closeArticle);
		that.children.article = new Article();
		console.log('Article Opened');
	}
	
	this.closeArticle = function () {
		console.log('Bon::closeArticle()');
		$(window).unbind('.ARTICLE');
		that.children.article = null;
		//console.log('Bon::closeArticle() article =', that.children.article);
		that.restoreScrollPosition();
	}
	
	this.scrollToTop = function () {
		$('html, body').animate({ scrollTop: 0 }, 'fast');
	}
	
	this.saveScrollPosition = function () {
		that.previousScroll = $(window).scrollTop();
		console.log('Bon::saveScrollPosition()', that.previousScroll);
	}
	
	this.restoreScrollPosition = function () {
		console.log('Bon::restoreScrollPosition()', that.previousScroll);
		$('html, body').animate({ scrollTop: that.previousScroll }, 'fast');
	}
	
	this.setupLandingPage = function () {
		if(location.pathname == "/" || location.pathname == "/start/" || location.pathname == "/live/" || location.pathname == "/live/start/") {
			console.log('Bon::layoutLandingPage()');
			that.landing = new Landing();
		}
	}
	
	return this;
};




