var log = function() {};
/**
 * SpriteButton
 * 
 * SpriteButtons are automatically generated from markup(if you look for target
 * etc., goto markup code)
 * 
 * @dependencies prototype 1.6.0.3
 */
var o;
var com = {};
com.femjoy = {};
o = com.femjoy.SpriteButton = function(id, sprite, width, height) {
	this.id = id;
	this.uid = -1;
	this.sprite = sprite;
	this.width = width;
	this.height = height;
	this.target = "";
	this.node = null;
	this.active = false;
	this.allowActiveState = false;
	this.initialize();
}
o.instanceCount = 0;
o.buttonTemplate = new Template('<a href="#{target}"><div id="#{spriteId}" onclick="com.femjoy.SpriteButtonManager.onClick(this, #{height})" onmouseover="com.femjoy.SpriteButtonManager.onMouseOver(this, #{height})" onmouseout="com.femjoy.SpriteButtonManager.onMouseOut(this)" style="display:block; width:#{width}px; height:#{height}px; background-image:url(#{sprite}); overflow:hidden;"></div></a>');
o.prototype.initialize = function() {
	com.femjoy.SpriteButton.instanceCount++;
	this.uid = "_sprite" + com.femjoy.SpriteButton.instanceCount;
	this.target = $(this.id).innerHTML;
	$(this.id).innerHTML = com.femjoy.SpriteButton.buttonTemplate.evaluate({ spriteId:this.uid, target:this.target, sprite:this.sprite, width:this.width, height:this.height });
}

/**
 * SpriteButtonManager
 */
com.femjoy.SpriteButtonManager = function() {}
o = com.femjoy.SpriteButtonManager;
o.buttons = new Hash();
o.containers = new Hash();
o.add = function (id, sprite, width, height) {
	var spriteButton = new com.femjoy.SpriteButton(id, sprite, width, height);
	com.femjoy.SpriteButtonManager.buttons.set(spriteButton.uid, spriteButton);
	com.femjoy.SpriteButtonManager.containers.set(spriteButton.id, spriteButton);
	return spriteButton;
}
o.onClick = function(spriteButton, height) {
	var btn = com.femjoy.SpriteButtonManager.buttons.get(spriteButton.id);
	if(btn.allowActiveState) {
		btn.active = btn.active ? false : true;
		if(btn.active)	spriteButton.style.backgroundPosition = "0px -" + height + "px";
		else			spriteButton.style.backgroundPosition = "0px 0px";		
	} else {
		spriteButton.style.backgroundPosition = "0px -" + height + "px";
	}
}
o.onMouseOver = function(spriteButton, height) {
	spriteButton.style.backgroundPosition = "0px -" + height + "px";
}
o.onMouseOut = function(spriteButton) {
	var btn = com.femjoy.SpriteButtonManager.buttons.get(spriteButton.id);	
	if(!btn.active) spriteButton.style.backgroundPosition = "0px 0px";
}

/**
 * Module
 */
com.femjoy.Module = function(id, name) {
	this.id = id;
	this.name = name;
	this.node = null;
	this.conf = null;
	this.initialize();
}
o = com.femjoy.Module.prototype;
o.initialize = function() {
	this.node = $(this.id);
	this.conf = { window:false, back:false, title:this.name, previous:null, fixedSize:true };
}

/**
 * ModuleTransitionManager
 * @dependencies Scriptaculous 1.8.2
 */
com.femjoy.ModuleTransitionManager = function() { }
o = com.femjoy.ModuleTransitionManager;
o.modules = new Hash();
o.currentModule = null;
o.windowLayout = null;
o.duration = 0.4;
o.movement = 320;
o.FORWARD = "forward";
o.BACKWARD = "backward";
o.direction = o.FORWARD; 
o.add = function(module) {
	com.femjoy.ModuleTransitionManager.modules.set(module.name, module);
}
o.show = function(module) {
	// check if there is a previous module to hide
	if(com.femjoy.ModuleTransitionManager.currentModule != null) {
		var currentModule = com.femjoy.ModuleTransitionManager.currentModule;
		new Effect.Move(currentModule.node, {	x: com.femjoy.ModuleTransitionManager.direction == com.femjoy.ModuleTransitionManager.FORWARD ? -com.femjoy.ModuleTransitionManager.movement : com.femjoy.ModuleTransitionManager.movement,
												y:0,
												mode:'absolute',
												duration:com.femjoy.ModuleTransitionManager.duration,
												afterFinish:function() { currentModule.node.style.left = -com.femjoy.ModuleTransitionManager.movement + 'px'; }
											 });
	}
	// reset start position
	module.node.style.left = com.femjoy.ModuleTransitionManager.direction == com.femjoy.ModuleTransitionManager.FORWARD ? com.femjoy.ModuleTransitionManager.movement + 'px' : -com.femjoy.ModuleTransitionManager.movement + 'px';
	// set window layout
	com.femjoy.ModuleTransitionManager.setWindowLayout(module.conf);
	// set display mode of module
	module.node.style.display = "block";
	// move module
	new Effect.Move(module.node, { x:0, y:0, mode:'absolute', duration:com.femjoy.ModuleTransitionManager.duration });
	// save reference to current module
	com.femjoy.ModuleTransitionManager.currentModule = module;	
}
o.setStartModule = function(module) {
	// set display mode of module
	module.node.style.display = "block";
	// set position (no transition for first start module)
	module.node.style.left = "0px";
	// setup window layout
	com.femjoy.ModuleTransitionManager.setWindowLayout(module.conf, true);
	// hide other modules
	com.femjoy.ModuleTransitionManager.modules.each(function(item) {
		if(module != item.value) item.value.node.style.left = -com.femjoy.ModuleTransitionManager.movement + "px";
	});
	// save current module
	com.femjoy.ModuleTransitionManager.currentModule = module;
}
// TODO create a own window layout class
o.setWindowLayout = function(conf) {
	if(arguments.length == 2) {
		var fast = arguments[1];
	} else {
		var fast = false;
	}
	
	if(fast) {
		if(conf.window) com.femjoy.ModuleTransitionManager.windowLayout.style.display = "block";
		else			com.femjoy.ModuleTransitionManager.windowLayout.style.display = "none";
		
		if(conf.back)	$('btn_window_back').style.display = "block";
		else			$('btn_window_back').style.display = "none";
	} else {
		Effect.Fade('windowTitle', { duration:0 } )
		Effect.Appear('windowTitle', { duration:0.3, delay:0.2 } )
		if(conf.window) Effect.Appear(com.femjoy.ModuleTransitionManager.windowLayout, { duration:0.2, afterFinish:function() { $('windowTitle').innerHTML = conf.title; } });
		else			Effect.Fade(com.femjoy.ModuleTransitionManager.windowLayout, { duration:0.2, afterFinish:function() { $('windowTitle').innerHTML = conf.title; } });
		
		if(conf.back)	$('btn_window_back').style.display = "block";
		else			$('btn_window_back').style.display = "none";		
	}
	// set title if fast	
	if(fast) $('windowTitle').innerHTML = conf.title;
	
	// set window size
	if(conf.fixedSize)	$('container').style.overflow = "hidden";
	else				$('container').style.overflow = "visible";
}
o.registerWindow = function(windowLayout) {
	com.femjoy.ModuleTransitionManager.windowLayout = $(windowLayout);
}

/* ########################## SITE SCRIPTS ########################## */

// templates
var photoListItem = new Template(	'<a href="javascript:loadDetailsPage(\'#{type}\', \'#{setcode}\')">' + 
									'<div class="photoListItem">' + 
									'<div class="thumb"><img src="http://femjoy.com/updates/#{setcode}/cover2_68x68.jpg" width="68" height="68" /></div>' +
									'<h5>#{title}</h5>' +
									'<h6>Artist</h6><div class="artist">#{artist}</div>' +
									'<div class="arrow"><img src="' + baseURL + '/public/img/iphone/listArrow.png" width="22" height="22" /></div>' + 
									'</div>' +
									'</a>');
									
var videoListItem = new Template(	'<a href="javascript:loadDetailsPage(\'#{type}\', \'#{setcode}\')">' + 
									'<div class="videoListItem">' + 
									'<div class="thumb"><img src="http://femjoy.com/updates/#{setcode}/cover2_142x68.jpg" width="142" height="68" /></div>' +
									'<h5>#{title}</h5>' +
									'<h6>Artist</h6><div class="artist">#{artist}</div>' +
									'<div class="arrow"><img src="' + baseURL + '/public/img/iphone/listArrow.png" width="22" height="22" /></div>' + 
									'</div>' +
									'</a>');

var videoDetail = new Template(		'<div class="videoDetail">' +
									'<div class="cover" id="dcontent">' +
									'<img src="http://femjoy.com/updates/#{setcode}/cover2_314x150.jpg" width="314" height="150" />' +
									'</div>' +
									'<a href="#{link}" ><div class="button" style="#{bgcolor}" ><img src="' + baseURL + '/public/img/iphone/videoDetailPlayBtn.png" width="312" height="72" /></div></a>' +
									'<div class="info">' +
									'<h6 style="#{color}">#{title}</h6>' +
									'<div class="modelT">Model</div>' +
									'<div class="model">#{model}</div>' +
									'<div class="artistT">Artist</div>' +
									'<div class="artist">#{artist}</div>' +
									'<div class="lengthT">Length</div>' +
									'<div class="length">#{length}</div>' +																
									'</div>' + 
									'<div class="bottom"><img src="' + baseURL + '/public/img/iphone/videoDetailBg.jpg" width="320" height="80" /></div>' +
									'</div>');

var galleryDetail = new Template(	'<div class="photoDetail">' +
									'<div class="cover" id="dcontent"><img src="http://femjoy.com/updates/#{setcode}/cover2_314x314.jpg" width="314" height="314" /></div>' +
									'<div class="info">' +
									'<h6 style="#{color}">#{title}</h6>' +
									'<div class="modelT">Model</div>' +
									'<div class="model">#{model}</div>' +
									'<div class="artistT">Artist</div>' +
									'<div class="artist">#{artist}</div>' +
									'<div class="picsT">Info</div>' +
									'<div class="pics">#{pics}</div>' +
									'<a href="#{link}"><div class="button" style="#{bgcolor}"><img src="' + baseURL + '/public/img/iphone/photoDetailArrow.png" width="76" height="69" /></div></a>' +									
									'</div>' + 
									'</div>');

var videoEmbedCode = new Template( '<embed src="http://femjoy.com/updates/#{setcode}/cover2_314x150.jpg" href="http://femjoy.com/members/content/#{setcode}/#{teaserfile}" type="video/x-m4v" target="myself" scale="1" width="320px" height="150px" />');

var menuLoader = new Element('div', { 'class':'loader', 'id':'loader' }).update('<img src="' + baseURL + '/public/img/iphone/loader.gif" width="16" height="16" />');
var detailLoader = new Element('div', { 'class':'dloader', 'id':'dloader' }).update('<img src="' + baseURL + '/public/img/iphone/dloader.gif" width="32" height="32" />');
									
// page navigation
var previousPage = null;
var currentPage = null;
function gotoPage(moduleName) {		
	var module = com.femjoy.ModuleTransitionManager.modules.get(moduleName);
	previousPage = currentPage;	
	com.femjoy.ModuleTransitionManager.show(module);
	currentPage = module;
	com.femjoy.ModuleTransitionManager.direction = com.femjoy.ModuleTransitionManager.FORWARD;
}
function gotoPrevious() {
	var prev;
	if(currentPage.conf.previous == null)	prev = previousPage.name;
	else									prev = currentPage.conf.previous.name	
	com.femjoy.ModuleTransitionManager.direction = com.femjoy.ModuleTransitionManager.BACKWARD;
	if(currentPage == com.femjoy.ModuleTransitionManager.modules.get('details')) $('detailsContainer').innerHTML = '';
	gotoPage(prev);
}
// content loaders
function loadContent(node, action, container) {
	$(node).insert(menuLoader);
	new Ajax.Request(baseURL + action, {
		method:'get',
		onSuccess:function(transport) {
			$('loader').remove();
			if(transport.responseJSON) {
				var json = transport.responseJSON;
				var str = '';
				switch(json["type"]) {
					case "videos":
						var videos = json["content"];
						for(var video in videos) {
							var artist = videos[video]['artist'];
							var title = videos[video]['title'];
							artist = artist.length > 12 ? artist.substr(0, 12) + '.' : artist;
							title = title.length > 20 ? title.substr(0, 20) + '.' : title;							
							str+= videoListItem.evaluate({setcode:videos[video]['SetCode'], title:title, artist:artist, type:'video'});
						}
						gotoPage('videos');
						break;
					case "galleries":
						var galleries = json["content"];			
						for(var gallery in galleries) {	
							var artist = galleries[gallery]['artist'];
							var title = galleries[gallery]['title'];
							artist = artist.length > 20 ? artist.substr(0, 20) + '.' : artist;
							title = title.length > 20 ? title.substr(0, 20) + '.' : title;
							str+= photoListItem.evaluate({setcode:galleries[gallery]['SetCode'], title:title, artist:artist, type:'gallery'});
						}						
						gotoPage('photos');
						break;
					case "pod":
						var pod = json["content"];
						str = '<div class="podItem"><img src="' + pod + '" width="320" height="427" /></div>';
						gotoPage('pod');
						break;
					case "join":
						var join = json["content"];
						gotoPage('join');
						break;
					default:
						str= "Error: Invalid JSON content type.";
				}
				$(container).innerHTML = str;
			}
		}
	});	
}
function loadDetailsPage(type, setCode) {
	// show loader
	$('container').insert(detailLoader);
	$('container').style.overflow = "hidden";
	new Effect.Opacity($('dloader'), { from:0, to:0.8, duration:0.5 });
	// define action, depends on content type
	var action = '/content/' + type;
	new Ajax.Request(baseURL + action, {
		method:'get',
		parameters:{contentId:setCode},
		onSuccess:function(transport) {
			$('dloader').remove();			
			if(transport.responseJSON) {
				var json = transport.responseJSON;
				var str = '';
				// get details module
				var module = com.femjoy.ModuleTransitionManager.modules.get('details');				
				switch(json["type"]) {
					case "video":
						var videos = json["content"];
						for(var video in videos) {
							str = videoDetail.evaluate({	setcode:videos[video]['SetCode'],
															title:videos[video]['title'],
															model:json['modelNames'],
															artist:videos[video]['artist'],
															length:videos[video]['min'] + ':' + videos[video]['sec'],
															color:'color:#' + videos[video]['color'],
															bgcolor:'background-color:#' + videos[video]['color'],
															link:'javascript:showFullMovie(\'' + videos[video]['SetCode'] + '\',  \'' + json['videoFile'] + '\')',
															teaserfile:json['teaserFile']
														});
							module.conf.title = videos[video]['title'];
							module.conf.previous = com.femjoy.ModuleTransitionManager.modules.get('videos');
						}
						break;
					case "gallery":
						var galleries = json["content"];
						for(var gallery in galleries) {
							str = galleryDetail.evaluate({	setcode:galleries[gallery]['SetCode'],
															title:galleries[gallery]['title'],
															model:json['modelNames'],
															artist:galleries[gallery]['artist'],
															pics:galleries[gallery]['pics'] + ' Pictures',
															color:'color:#' + galleries[gallery]['color'],
															bgcolor:'background-color:#' + galleries[gallery]['color'],
															link:'javascript:openPhotoViewer(\'' + galleries[gallery]['SetCode'] + '\', 0)'
														});
							module.conf.title = galleries[gallery]['title'];
							module.conf.previous = com.femjoy.ModuleTransitionManager.modules.get('photos');
						}						
						break;
					default:
						str = 'Error: Invalid JSON content type.';
				}
				$('detailsContainer').innerHTML = str;
				gotoPage('details');
			}
		}
	});
}
function openPhotoViewer(setCode, page) {
	// show loader
	$('container').insert(detailLoader);
	new Effect.Opacity($('dloader'), { from:0, to:0.8, duration:0.5 });
	// define action, depends on content type
	var action = '/content/galleryoverview';
	new Ajax.Request(baseURL + action, {
		method:'get',
		parameters:{contentId:setCode},
		onSuccess:function(transport) {
			$('dloader').remove();
			if(transport.responseJSON) {
				var json = transport.responseJSON;
				var str = '';
				// get photoviewer
				var module = com.femjoy.ModuleTransitionManager.modules.get('photoviewer');				
				var str = '';
				var maxRows = 4;
				var maxCols = 4;				
				var maxPages = Math.round(json.content.length / (maxRows * maxCols) - 1);								
				// check page
				var cStart;		
				if(page <= maxPages) {
					cStart = page * maxRows * maxCols;
				} else {
					cStart = jsonObj.content.length - maxRows * maxCols;
					page = maxPages;
				}
				var count = 0;
				for(var c = cStart; c < json.content.length; c++) {
					var style = 'photoViewerThumb';
					if(count == 0 || ((count - 2 > 0) && count % maxCols == 0)) style+= ' first';
					if((count + 1) % maxCols == 0) style+= ' last';
					str+= '<div class="' + style + '" onclick="javascript:loadPhoto(\'' + setCode + '\', \'' + json.content[c] + '\')" ><img id="thumb' + count + '" src="http://femjoy.com/updates/' + setCode + '/thumbs68/' + json.content[c] + '" width="68" height="68" /></div>';
					if(count == (maxCols * maxRows) - 1) break;					
					count++;
				}
				// prev/next buttons
				var prevButton = $('viewerNaviPrev');
				var nextButton = $('viewerNaviNext');
				
				if(page > 0) {
					prevButton.onclick = function() { openPhotoViewer(setCode, page - 1); };
					new Effect.Opacity(prevButton, { to:1.0 });
				} else {
					prevButton.onclick = null;
					new Effect.Opacity(prevButton, { to:0.2 });			
				}
				if(page < maxPages) {
					nextButton.onclick = function() { openPhotoViewer(setCode, page + 1); };
					new Effect.Opacity(nextButton, { to:1.0 });
				} else {
					nextButton.onclick = null;
					new Effect.Opacity(nextButton, { to:0.2 });			
				}				
				// fill pages
				$('viewerNaviPages').innerHTML = 'Page ' + (page + 1) + ' of ' + (maxPages + 1);
				// fill viewer
				$('viewerPhotos').innerHTML = str;
				// goto viewer 
				if(com.femjoy.ModuleTransitionManager.currentModule != module) gotoPage('photoviewer');
			}
		}
	});	
}
var currentPhoto = null;
function loadPhoto(setCode, photoFileName) {
	// show loader
	$('container').insert(detailLoader);
	new Effect.Opacity($('dloader'), { from:0, to:0.8, duration:0.5 });
	// load photo
	var photoUrl = 'http://femjoy.com/members/content/' + setCode + '/S/' + photoFileName;
	var photo = new Image();
	photo.onload = function() { photoLoaded(photo); };
	photo.width = 320;
	photo.src = photoUrl;
	currentPhoto = photo;
}
function photoLoaded(photo) {
	// remove loader
	$('dloader').remove();
	// display photo
	$('viewerPhotoLarge').insert(photo);
	$('viewerPhotoLarge').style.display = "block";
	$('btn_viewer_exit').style.display = "block";
	// allow scaling
	$('viewport').content = 'width=device-width; initial-scale=1.0;';
}
function closePhoto() {
	// hide photo large viewer
	$('viewerPhotoLarge').style.display = "none";
	$('btn_viewer_exit').style.display = "none";
	// unload photo
	currentPhoto.remove();
	// reset viewport
	$('viewport').content = 'width=device-width; initial-scale=1.0;';
}
function showFullMovie(setCode, videoFile) {
	// force member login
	var cImg = new Image();	
	cImg.onload = function() {
		$('dcontent').innerHTML = videoEmbedCode.evaluate({setcode:setCode, teaserfile:videoFile });
	}
	cImg.src = 'http://femjoy.com/members/clear.gif';
}
// member options
function saveWelcomeEnabled(btn) {
	var btn = com.femjoy.SpriteButtonManager.containers.get($(btn).id);
	welcomeEnabled:btn.active
	UserData.db.transaction(
		function (transaction) {
			var sql = 'UPDATE ' + UserData.dbName + ' SET showWelcome = ? WHERE 1=1;';
			transaction.executeSql(sql, [btn.active ? "1" : "0"], nullDataHandler, errorHandler);
		}
	);		
}
function logout() {
	if(UserData.passwordProtect) {
		$('appPasswordInputField').value = "";
		$('appPassword').show();
	} else {
		gotoPage("welcome");
	}
}
function insertApplicationPassword(btn, inputId) {
	var btn = com.femjoy.SpriteButtonManager.containers.get($(btn).id);
	if(btn.active) {
		new Effect.Appear(inputId);
	} else {
		new Effect.Fade(inputId);
		// Clear password in database
		UserData.db.transaction(
			function (transaction) {
				var sql = 'UPDATE ' + UserData.dbName + ' SET passwordProtected = ?, password = ? WHERE passwordProtected = "1";';
				transaction.executeSql(sql, ["0", ""], nullDataHandler, errorHandler);
				UserData.passwordProtect = 0;
				UserData.password = "";
			}
		);		
	}
}
function validatePassword(id, saveButtonId) {
	if(String($(id).value).length > 3) {
		new Effect.Appear(saveButtonId, {duration:0.2});
	} else {
		new Effect.Fade(saveButtonId, {duration:0.2});
	}
}
function saveAppPassword(btn, inputId) {
	var btn = com.femjoy.SpriteButtonManager.containers.get($(btn).id);
	// Save Password to Database
	UserData.db.transaction(
		function (transaction) {
			var sql = 'UPDATE ' + UserData.dbName + ' SET passwordProtected = ?, password = ? WHERE passwordProtected = "0";';
			transaction.executeSql(sql, ["1", String($(inputId).value)], nullDataHandler, errorHandler);
		}
	);
	new Effect.Fade($(btn).id);
}
function showCheckAppPassword(checkButtonId) {
	new Effect.Appear(checkButtonId, { duration:0.3 });
}
function checkAppPassword(inputId, password) {
	if($(inputId).value == UserData.password) {
		new Effect.Fade('appPassword', { duration:0.5 });
	} else {
		new Effect.Appear('wrongAppPassword', { duration:0.5 });		
	}
}
function hideWrongPasswordMessage() {
	new Effect.Fade('wrongAppPassword', { duration:0.5 });
}

function successHandler() {}
function nullDataHandler(transaction, results) {}
function errorHandler(error) {
	if(error.code == "1") {
		// Table already exists, is not an error
	} else {
		//alert("Error: " + error.code + ", " + error.message);
	}
	return false;
}

// UserData
var UserData = {
	db:null,
	dbName:"userdata",
	version:"1.0",
	dbFullName:"User Database",
	init:function() {},
	maxSize:65536,
	showWelcome:true,
	passwordProtect:false,
	password:""
};
// Initialize WebApp
document.observe("dom:loaded", function() {
	// Create UserTable	
	function createUserTable() {
		tableExists(UserData.dbName, createUserTableHandler)		
	}
	
	function createUserTableHandler(exists) {
		if(!exists) {
			UserData.db.transaction(
				function(transaction) {
					// Create table if not exists and fill with default values
					var sql = 'CREATE TABLE IF NOT EXISTS ' + UserData.dbName + ' (' +
							  'showWelcome BOOL NOT NULL DEFAULT "1", ' +
							  'passwordProtected BOOL NOT NULL DEFAULT "0", ' +
							  'password VARCHAR( 32 ) NULL);';
					transaction.executeSql(sql, [], nullDataHandler, errorHandler);
					
					// Fill table with default values
					var sql = 'INSERT INTO ' + UserData.dbName + ' (showWelcome, passwordProtected, password) VALUES (?, ?, ?);';
					transaction.executeSql(sql, ["1", "0", ""], nullDataHandler, errorHandler);				
				}
			);			
		}
		readValues();
	}
	
	function readValues() {
		// Read Values
		UserData.db.transaction(
			function(transaction) {
				// Read all values from userdata
				var sql = 'SELECT * FROM ' + UserData.dbName + ';';
				transaction.executeSql(sql, [], function(transaction, results) {
					UserData.showWelcome		= Boolean(results.rows.item(0)['showWelcome']);
					UserData.passwordProtect	= Boolean(results.rows.item(0)['passwordProtected']);
					UserData.password			= results.rows.item(0)['password'];
					// Call DBInit method
					UserData.init.call(this);			
				});
			}
		)
	}
	
    function tableExists(tableName, handler) {
    	UserData.db.transaction(    		
    		function(transaction) {
    			var sql = "SELECT count(name) as count FROM sqlite_master WHERE ((type = 'table') AND (name = '" + tableName + "'))";
    			transaction.executeSql(sql, [], function(transaction, results) {
    				if(results) {
    					handler.call(this, results.rows.item(0)['count'] > 0);
    				} else {
    					handler.call(this, false);
    				}
    			});
    		}
    	);
    }
	
	// Open JS Database Connection
    // TODO If there is no user-database, initialize instantly, otherwise add
	try {
		if(!window.openDatabase) {
			init();
		} else {
			// Init Values
			UserData.db = openDatabase(UserData.dbName, UserData.version, UserData.dbFullName, UserData.maxSize);
			UserData.init = init;
			// Create Table if not exists
			createUserTable();
		}
	} catch(e) {
		if(e == 2) {
			//alert("Invalid Database Version.");
		} else {
			//alert("Unknown error " + e + ".");
		}
	}
}); 

function init() {
	// Add sprite buttons
	com.femjoy.SpriteButtonManager.add('btn_welcome_enter', baseURL + '/public/img/iphone/btn_goto.jpg', 45, 45);
	com.femjoy.SpriteButtonManager.add('btn_window_back', baseURL + '/public/img/iphone/windowTitleBack.jpg', 45, 45);
	com.femjoy.SpriteButtonManager.add('btn_viewer_exit', baseURL + '/public/img/iphone/btn_check.png', 45, 45);
	var btn_option1 = com.femjoy.SpriteButtonManager.add('btn_members_welcome_screen', baseURL + '/public/img/iphone/btn_checkBox.jpg', 45, 45);
	btn_option1.allowActiveState = true;
	if(UserData.showWelcome) {
		btn_option1.active = false;
	} else {
		btn_option1.active = true;
	}
	com.femjoy.SpriteButtonManager.onClick($(btn_option1.uid), 45); 
	com.femjoy.SpriteButtonManager.add('btn_members_anonymous_surfing', baseURL + '/public/img/iphone/btn_go.jpg', 45, 45);
	var btn_option3 = com.femjoy.SpriteButtonManager.add('btn_members_application_password', baseURL + '/public/img/iphone/btn_checkBox.jpg', 45, 45);
	btn_option3.allowActiveState = true;
	if(UserData.passwordProtect) {
		$('appPassword').show();
		btn_option3.active = false;		
	} else {
		$('appPassword').hide();
		btn_option3.active = true;
	}
	com.femjoy.SpriteButtonManager.onClick($(btn_option3.uid), 45);
	com.femjoy.SpriteButtonManager.add('btn_save_app_password', baseURL + '/public/img/iphone/btn_saveAppPassword.png', 39, 40);
	com.femjoy.SpriteButtonManager.add('btn_insert_app_password', baseURL + '/public/img/iphone/btn_saveAppPassword.png', 39, 40);
	// Create modules
	var welcome = new com.femjoy.Module('welcome', 'welcome');
	var menu	= new com.femjoy.Module('menu', 'menu');
	menu.conf.window = true;
	menu.conf.title = '<img src="' + baseURL + '/public/img/iphone/menuTitle.png" width="120" height="19" />';
	var photos	= new com.femjoy.Module('photos', 'photos');
	photos.conf.window = true;
	photos.conf.back = true;
	photos.conf.title = "FEMJOY Photos";
	photos.conf.previous = menu;
	photos.conf.fixedSize = false;
	var videos = new com.femjoy.Module('videos', 'videos');
	videos.conf.window = true;
	videos.conf.back = true;
	videos.conf.title = "FEMJOY Videos";
	videos.conf.previous = menu;
	videos.conf.fixedSize = false;
	var pod		= new com.femjoy.Module('pod', 'pod');
	pod.conf.window = true;
	pod.conf.back = true;
	pod.conf.title = "FEMJOY Picture of the Day";
	var join	= new com.femjoy.Module('join', 'join');
	join.conf.window = true;
	join.conf.back = true;
	join.conf.title = "Join FEMJOY";
	join.conf.previous = menu;
	var members	= new com.femjoy.Module('members', 'members');
	members.conf.window = true;
	members.conf.back = true;
	members.conf.title = "FEMJOY Members Home";
	members.conf.previous = menu;
	var contact = new com.femjoy.Module('contact', 'contact');
	contact.conf.window = true;
	contact.conf.back = true;
	contact.conf.title = "Contact";
	contact.conf.previous = menu;
	var details		= new com.femjoy.Module('details', 'details');
	details.conf.window = true;
	details.conf.back = true;
	details.conf.title = "Media Details";
	var photoviewer = new com.femjoy.Module('photoviewer', 'photoviewer');
	photoviewer.conf.window = true;
	photoviewer.conf.back = true;
	photoviewer.conf.title = "FEMJOY Photoviewer";
	// add modules
	com.femjoy.ModuleTransitionManager.add(welcome);
	com.femjoy.ModuleTransitionManager.add(menu);
	com.femjoy.ModuleTransitionManager.add(photos);
	com.femjoy.ModuleTransitionManager.add(videos);
	com.femjoy.ModuleTransitionManager.add(pod);
	com.femjoy.ModuleTransitionManager.add(join);
	com.femjoy.ModuleTransitionManager.add(members);
	com.femjoy.ModuleTransitionManager.add(contact);
	com.femjoy.ModuleTransitionManager.add(details);
	com.femjoy.ModuleTransitionManager.add(photoviewer);
	// register window layout
	com.femjoy.ModuleTransitionManager.registerWindow('window');
	// set start module
	if(UserData.showWelcome) {
		com.femjoy.ModuleTransitionManager.setStartModule(welcome);
		// set currentPage
		currentPage = welcome;
	} else {
		com.femjoy.ModuleTransitionManager.setStartModule(menu);
		// set currentPage
		currentPage = menu;
	}
}
