
# WARNING: This files gets loaded both in the context of the login.htm and the main UI sw.htm
# 		   In the context of sw.htm, the background gets initialised fullscreen and later as a small image top left

function dge(a) {return document.getElementById(a);}
function defined(o) 
{
	if(o===undefined || o===null) return false;
	return true;
}

var std_appearances={
	traditional: {raw_css:'background:#A0BFE8 url(||www_base||background/gradient_linear.jpg) repeat-x; height: 100vh;'},
	modern: {raw_css:'background:#6699c2 url(||www_base||background/THE_IMAGE) no-repeat fixed; background-size: cover; background-position: 35%, 50%; height: 100vh;'},
};

var appearances=[];
var appearance_presets = ||tcmd_newlook_presets||;

function appearance_defaults()
{
	for (name in std_appearances) {
		std_appearances[name].name=name;
	}

	appearance_add_std( 'traditional', 'login_box_oldststyle');
	appearance_add_std( 'modern', 'login_box_blurred');
}

function appearance_attribution()
{
	var desc = '';
	if(defined(ui_look.email) && (ui_look.email.length>0)) {
		desc = 'look by '+ui_look.email;	
	}	
	var el = dge('appearance_info2');
	if(defined(el)) el.innerHTML = desc;

	desc = '';	
	if(defined(ui_look.email) && (ui_look.email.length>0)) {
		desc = 'Custom look ACTIVE (associated with '+ui_look.email+')';	
	} else if (ui_look.custom){
		desc = 'Custom look ACTIVE';	
	}
	
	el = dge('custom_status');
	if(defined(el)) el.innerHTML = desc;
}

function appearance_set(el_id, appearance_index	)
{
	var appearance = appearances[appearance_index];

	if(el_id=="appearance_bg"){
		set_login_box(appearance.box);
	}
	var el = dge(el_id);
	if(!el) return;

	el.className="";
	el.style.cssText = '';
	var appearance = appearances[appearance_index];
	if(!appearance) return;
	el.appearance_index = appearance_index;
	el.className = appearance.class;
	el.style.cssText = appearance_stdlook(appearance.raw_css);

||if_not(newlook_propagate_disable)||
	if(el_id=="appearance_bg"){
		var el = dge("loading_ajax");
		if(!el) return;

		var hidden = class_contains(el,'hidden');

		el.className="";
		el.style.cssText = '';
		var appearance = appearances[appearance_index];
		if(!appearance) return;
		el.appearance_index = appearance_index;
		el.className = appearance.class;
				
		if(defined(window.sw_login_raw_css)){
			el.style.cssText = appearance_stdlook(window.sw_login_raw_css);				
		} else {
			el.style.cssText = appearance_stdlook(appearance.raw_css);		
		}
		
		if (hidden) class_add(el, 'hidden');
	}
||endif||
	
	ui_look.login_style = appearance.box;
	ui_look.ui_style = appearance.name;
	ui_look.standard_image = window.current_modern_image;
	ui_look.custom = false;
	if(appearance_index==0) ui_look.custom = true;
	if(window.current_modern_image != appearance_presets.images[0])  ui_look.custom = true;
	calculate_sizes();	
	appearance_attribution();
}
function set_login_box(box)
{
	var el=document.body;
	class_remove(el,'login_box_oldststyle');
	class_remove(el,'login_box_shadow');
	class_remove(el,'login_box_blurred');
	class_add(el,box);
	el.appearance_box=box;
}

function appearance_increment(e)
{
	var el = dge("appearance_bg");
	if(!el) return;

	var appearance_index = el.appearance_index+1;
	if(appearance_index>=appearances.length){
		appearance_index=0;
	}

	ui_look.mode = 'preset';
	appearance_set("appearance_bg", appearance_index);
	appearance_save();
}
function appearance_add_std(type, box)
{
	var bg=std_appearances[type];
	if(!bg) return;
	if(bg.class==undefined) bg.class='';
	if(bg.raw_css==undefined) bg.raw_css='';
	appearances.push( {name:bg.name, class:bg.class, raw_css:bg.raw_css, box:box } );
}

# dummy function to get replaced later by loading ui
function custom_bg_update(background)
{
	var el=dge('loading');
	el.style.background = 'url('+background+') no-repeat fixed';
	el.style.backgroundSize = 'cover';
	el.style.backgroundPosition = '50%, 50%';
	el.style.height = '100vh';

	window.sw_login_raw_css = el.style.cssText;
		
}

function appearance_change()
{
	dge('appearances').innerHTML = appearance_all_html();
	
	//custom_bg_update();	<<< call this instead!!
	var el = dge('custom_button');
	if(el){
		el.style.cssText = 'background:url('+ui_look.custom_image+')';
		el.style.backgroundSize = 'cover';
	}
	
	class_remove(dge('choose_custom'),'hidden');
}
function appearance_done()
{
	class_add(dge('choose_custom'),'hidden');
}


function appearance_preset(type)
{
	window.current_modern_image = appearance_imagetext(type);
	var index = 1;
	if(type==-1) index=0;
	
	ui_look.mode = 'preset';
	appearance_set("appearance_bg", index);	
	appearance_save();
}
function appearance_stdlook(css_txt)
{
	return css_txt.replace('THE_IMAGE',appearance_presets.location+window.current_modern_image);
}
function appearance_imagetext(type)
{
	var img_txt = 'default.jpg';	
	img_txt=appearance_presets.images[type];
	return img_txt;
}
function appearance_custom_restore()
{
	if(ui_look.custom_image==null) return;
	ui_look.mode = 'custom';
	custom_bg_update(ui_look.custom_image);
	appearance_save();
}

function appearance_presets_html()
{
	var txt='';
	var items = appearance_presets;
	if(appearance_presets==U) items = {location:'', images:['default.jpg']};
	for(var i=0;i<items.images.length;i++){
		txt+='<td class="tbtn" style="padding:5px;"><div class="tbtn" style="background:url(||www_base||background/'+items.location+items.images[i]+'); background-size: cover;" onclick="appearance_preset('+i+')"></div></td>';
	}
	return txt;
}
function appearance_all_html()
{
	var custom = '';
||if_not(newlook_custom_photo_disable)||
	custom = '||html_begin()||\
		<td>Custom:</td>
			<td><div id="custom_button" class="tbtn" onclick="appearance_custom_restore()"></div></td>
		 ||html_end()||';
||endif||		
	
	return '||html_begin()||\
	  <table style="display:inline-table"><tr>
	   	 '+custom+'
	   <td>Standard:</td>
	   	 '+appearance_presets_html()+'
||if_not(newlook_old_photo_disable)||
 	   <td>Old:</td>
		<td><div class="tbtn" style="background:url(||www_base||background/gradient_linear.jpg); background-size: contain;" onclick="appearance_preset(-1)"></div></td>
||endif||		
	  </tr></table>
	  ||html_end()||';
}


# appearance primary state storage:
var ui_look={};

function appearance_load()
{
	if (!defined(localStorage)) return;
	ui_look = null;		
	if (ui_look==null) {
		var txt = localStorage.getItem('ui_look');
		if(txt!='undefined'){
			ui_look = JSON.parse(txt);
			if(ui_look!=null) ui_look.storage='local';
		}
	}
	if (ui_look==null) {
		var txt = sessionStorage.getItem('ui_look');
		if(txt!='undefined'){
			ui_look = JSON.parse(txt);
			if(ui_look!=null) ui_look.storage='session';
		}
	}
	if (ui_look==null) {
		ui_look = {
			mode:'preset',
			login_style:'login_box_blurred', ui_style:'modern', 
			standard_image:appearance_presets.images[0], custom_image:null, 
			email:'', storage:'none'
		}
	}
}
function appearance_save()
{
	if (!defined(localStorage)) return;
	
	if(ui_look.storage=='local'){
		localStorage.setItem('ui_look', JSON.stringify(ui_look));	
	}else{
		sessionStorage.setItem('ui_look', JSON.stringify(ui_look));	
	}

}
function appearance_persist()
{
	var orig_email = ui_look.email;
	ui_look.email = email;
	
	if(ui_look.storage=='none') return;
	if(ui_look.storage=='local' && ui_look.email == orig_email) return;
	
	localStorage.removeItem('ui_look');
	ui_look.storage='local';	
	appearance_save();
}


function appearance_init(el_id, logged_in)
{
	appearance_load();
	
	if(logged_in){
		appearance_persist();
	}

	custom_bg_init();
	appearance_defaults();
	
	var appearance_image = "";
	if(defined(appearance_presets.images) && appearance_presets.images.length>0){
		appearance_image = appearance_presets.images[0];
	}
	
	// appearances[].name traditional|modern
	// cookie = "modern|login_box_blurred|seascape.jpg"
	var appearance_index = 1;
	for(var index=0; index<appearances.length; index++){
		var appearance = appearances[index];
		if(appearance.name==ui_look.ui_style && appearance.box==ui_look.login_style){
			appearance_index = index;
			appearance_image = ui_look.standard_image;
			break;
		}
	}
	window.current_modern_image = appearance_image;
	appearance_set(el_id, appearance_index);
	appearance_attribution();
	
	custom_bg_init();	
}

function custom_bg_init()
{

||if_set(newlook_custom_photo_disable)||
	if(window.custom_bg_default && !sw.custom_logo) window.custom_bg_default();
	return;
||endif||
	
	var valid = defined(ui_look.custom_image) && ui_look.mode == 'custom';
	if(!valid) {
		if(window.custom_bg_default && !sw.custom_logo) window.custom_bg_default();
		return;
	}

	custom_bg_update(ui_look.custom_image);
}

function appearance_reset()
{
	sessionStorage.removeItem('ui_look');
	localStorage.removeItem('ui_look');
	ui_look.custom = false;
	ui_look.mode = 'preset';
	
	appearance_init('appearance_bg');

	var el = dge('custom_button');
	if(el){
		el.style.cssText = 'background:url('+ui_look.custom_image+')';
		el.style.backgroundSize = 'cover';
	}	
	
}


function make_image_canvas(x,y)
{
	var canvas = document.createElement('canvas');
	canvas.width = x; 
	canvas.height = y; 
	return canvas;
}
function reduce_image_raw(image, max_dim)
{
	var result = {img:image.img, height:image.height, width:image.width};
	var last_draw = image.img;
	while (result.height>max_dim.height && result.width>max_dim.width){		
		var oc = make_image_canvas(result.width/2, result.height/2);
		var octx = oc.getContext('2d');
		octx.drawImage(last_draw, 0, 0, oc.width, oc.height);
		result.canvas = oc;
		result.width = result.width/2;
		result.height = result.height/2;
	}
	return result;
}
function reduce_image_url(image, max_dim)
{
	var src = {img:image, canvas:U, ctx:U, height:image.height, width:image.width}
	var raw = reduce_image_raw(src,max_dim);
	if(raw.canvas==undefined) return null;		
	return raw.canvas.toDataURL("image/jpeg");
}

function custom_bg_drop(e)
{
	var files = defined(e.dataTransfer) ?  e.dataTransfer.files : e.target.files;
	var file = files[0];
	if(file.type=='image/jpeg' || file.type=='image/png'){
	}else{
		alert('Invalid file type: '+file.type);
		return stopEvent(e);
	}

	if(file.size>50000000) {
		alert('File too big')
		return stopEvent(e);
	}

	var reader = new FileReader();
	reader.onload = function(e) {
		var background = e.target.result;
		var img = new Image;
		img.src = background;
		img.onload = function(e){

			var reduced_background = reduce_image_url(img, {width:3000, height:3000});
			if(reduced_background){
				background = reduced_background;
			}
			if(!custom_background_set(background)){
				return
			}
			custom_bg_update(background);
		}

	}
	reader.readAsDataURL(file);
}

// Maybe generalise / pull into _appearance.js custom_bg_drop as well!
function custom_background_set(background)
{
	try{
		ui_look.custom_image = background;
		ui_look.mode = 'custom';
		appearance_save();
		return true;
	}catch(err){
		var err_txt = err.name ? err.name : err.message;
		alert('Error saving custom background: '+err_txt);
		return false;
	}
}