var autoSave = false;
var cancel = false;
var isWiki = false;
var locked = false;
function done() {
	if (!checkStep1()) return false;
	if (!checkStep5()) return false;
	if (!isFlash() && multi_selector.count > 1){
		selectStep(2);
		autoSave = true;
		uploadSubmit(user_id, post_id);
	} else {
		formSubmit();
	}
}

function isFlash() 
{
	return $('FlashFilesUpload');
}

function checkStep1()
{
	if($('post-title').value.length==0) {
		alert('Please enter a title for your article');
		$('post-title').focus();
		return false;
	}
	else {
		var els = $A(document.getElementsByTagName('select'));
		var selected = false;
		els.each(function(el) {
			if (el.id.indexOf('id_country_') != -1 && el.value != '')
				selected = true;
		});
		if (!selected) {
			alert('Please select destination.');
			return false;
		}
	}
	return true;
}

function checkStep5()
{
	if (!$('post-agree').checked)
	{
		alert('You need to certify this article.');
		selectStep(5);
		$('post-agree').focus();
		return false;
	}
	return true;
}

/* Copy step1-form fields to post-form. */
function copyStep1FormFields() 
{
	var fromElements = Form.getElements('step1-form'), toInputs = Form.getInputs('post-form', 'hidden');
	var gotIt = false;
	
	toInputs.each(function (to) {	//remove all destinations first
		if (to.name.indexOf('data[Destination]') != -1)
			to.remove();
	});
	toInputs = Form.getInputs('post-form', 'hidden');	//get list again
	fromElements.each(function (frm) {
		gotIt = false;
		toInputs.each(function (to) {
			if (to.name == frm.name) {	//Exists, then change the value.
				to.value = frm.value;
				gotIt = true;
			}	//end if
		});
		if (!gotIt) {	//Doesn't exist, then create a hidden input field.
			var hidden = document.createElement('input');
			hidden.type  = "hidden";
			hidden.name  = frm.name;
			hidden.value = frm.value;
			$('post-form').appendChild(hidden);
		}	//end if
	});
}

function formSubmit()
{
	if ($('edit_cancel')) {	//edit post
		if (!checkStep1())	return false;
		try	{
			updatePostBody();
			copyStep1FormFields();
			$("sorting_input").value = Sortable.serialize("sortable_photos");
		 	$("deleted_input").value = deletedPhotos.toString();
		} catch(e) { 
			// alert(e);
		}
	}
	if ($('edit_cancel')) {	//edit post
		new Effect.SlideUp('editpost', {
			duration: 1,
			beforeStart: function() {
				$('preview_message').hide();
				//swap the cancel with the edit post tab again
				$('edit_slide_down').show();
				$('edit_cancel').hide();					
				if (isFlash()) {
					// Flash.removeAll();
					$('uploader_div').hide();
				}	
				cancel = true;		
				selectStep(1);
				//clean the destiantion select box area
				Element.update('destinations', '');		
			},
			afterFinish: function() {
				$('post-form').submit();
			}
		});			
	} else {	//add post
		$('post-form').submit();
	}
}

function uploadSubmit(user_id, post_id)
{
	if (!isFlash() && multi_selector.count > 1) {
		var f = $('step2-form');
		var action = f.action;
		f.action = webroot + 'posts/upload/' + user_id + '/' + post_id + '/1';
		f.target = 'upload_iframe';
		uploadLoading();
		f.submit();
		f.action = action;
		f.target = '_self';
	}
}

function uploadLoading()
{
	Form.Element.disable('btn_upload');
	Element.update('upload_message', 'Uploading ....');
}

function uploadDone(error)
{
	newPhotos = true;
	Form.Element.enable('btn_upload');
	if (multi_selector)
		multi_selector.removeAll();	
	
	if(error==2) {
		Element.update('upload_message', 'Error occured while uploading one of the files (not an image) !');
		return;
	}
	else if(error==1) {
		Element.update('upload_message', 'Error occured while uploading one of the files (corrupted file) !');
		return;
	}
	else {
		Element.update('upload_message', 'Done.');
		toStep3();
	}	
}

var newPhotos = true;	//upload new photos? for photos cache
function loadPhotos() {
	if (!newPhotos) {
		$('loading_step3').hide();		
		$('show3').show();		
		return;
	}
	// load photos from server.
	$('show3').hide();
	$('loading_step3').show();
	new Ajax.Updater('show3', webroot+'posts/show3/'+post_id, {
	 	onComplete:function(request){
			$('loading_step3').hide();		
			$('show3').show();
			scroller.init();	//@todo This will consume 100% cpu.
			handleChanges();
			newPhotos = false;
		}, asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'show3']});
}

function toStep3() {
	//this is needed for automate from step 2 to step 3 after successfull upload
	selectStep(3);	
	loadPhotos();
	if(autoSave) formSubmit();
}

var targetStep = 0;
function selectStep(id)
{
	if (!cancel && Element.visible('step1') && !checkStep1()) {
		return false;
	}
	
	if (!cancel && Element.visible('step4')) {
		updatePostBody();
	}

	// Disable auto-upload.
	// if (!cancel && Element.visible('step2') && isFlash() && uploadSelectedFiles()) {
	// 	targetStep = id;
	// 	return;	//uploading files. waiting ....
	// }	
	
	for(i=1; i<=5; i++)
	{
		$('step'+i).hide();
		$('link_step'+i).className = 'notselected';
	}
	$('step'+id).show();
	$('link_step'+id).className = 'selected';
	
	if(id==2 && $('upload_message')) {
		Element.update('upload_message', '');
	}
	
	//fixing the FCKEditor, else it stalls in Firefox
	if (id == 4) {
		wakeUpEditor();
	}
	// $('preview_message').hide();
	if (!cancel)
		preview.show(false, true);
	handleChanges();
	if (id == 4) isFirstTime = false;
}

function showPreview() {
	// $('preview_message').hide();
	preview.show(true);
}

//Watch for modifications in the form fields.
var forms_changed = false;
function handleChanges() {
	var fields = $("steps").getElementsByTagName("input");
	for(var i=0;i<fields.length; i++) {
		//Ahsan: changed the code below to prototype event handler, as prototype adds rather than over-write the handler
		//needed to do this coz there is a need to add more onchange events
		Event.observe(fields[i], 'change', function() {window.forms_changed = true});
		/*
		fields[i].onchange=function() {
			window.forms_changed = true;
		}*/
	}
	var textareas = $("steps").getElementsByTagName("textarea");
	for(var i=0;i<textareas.length; i++) {
		Event.observe(textareas[i], 'change', function() {window.forms_changed = true});
	}
}

var rte = null;
/* Initialize RTE */
function initEditor() 
{
	initRTE(webroot+'js/rte/images/', webroot+'js/rte/', '', true);
	var options = {
		html: $F('PostBody'), 
		width: 490,
		height: 200,
		toolbar1: false,
		toggleSrc: false,
	    cmdUnderline: true,
	    cmdStrikethrough: false,
	    cmdSuperscript: false,
	    cmdSubscript: false,
	    cmdJustifyLeft: false,
	    cmdJustifyCenter: false,
	    cmdJustifyRight: false,
	    cmdJustifyFull: false,
	    cmdInsertHorizontalRule: false,
	    cmdInsertOrderedList: false,
	    cmdInsertUnorderedList: false,
	    cmdOutdent: false,
	    cmdIndent: false,
	    cmdForeColor: false,
	    cmdHiliteColor: false,
	    cmdInsertLink: true,
	    cmdInsertImage: false,
	    cmdInsertSpecialChars: true,
	    cmdInsertTable: false
		};
	rte = new richTextEditor('rte');
	$H(options).each(function(v) {
		rte[v.key] = v.value;
	});
}

/* Update PostBody hidden field with editor content. */
var isFirstTime = true;
function updatePostBody()
{
	if (isFirstTime || !$('hdnrte'))	return;
	
	var oldContent, newContent;
	updateRTEs();
	oldContent = $F('PostBody');
	newContent = htmlDecode($('hdnrte').value);
	if (newContent == 'undefined')	return;
	$('PostBody').value = filterContent(newContent);
	if (oldContent != newContent)
		window.forms_changed = true;
}

function filterContent(content)
{
	content = content.replace(/<object.*<\/object>/ig, '').
			replace(/<embed.*<\/embed>/ig, '').
			replace(/<img[^>]*>/ig, '');
	return content;
}

function wakeUpEditor()
{
	if ($('hdnrte')) {	//has built
		if ($B.isSafari) {
			rte.html = $F('PostBody').replace(/\'/ig, '&#39;').replace(/\n/ig, '').replace(/\r/ig, '');	//Fix Safari bug.
			rte.initDesignMode();
		} else {	//other browsers
            setHtmlSrc('rte', $F('PostBody').replace(/\'/ig, '&#39;').replace(/\n/ig, '').replace(/\r/ig, ''));
		}
		return;
	}
	rte.build('rte-container');
}

function setFormChange(state){
	forms_changed = state;
	alert("changed");
}

function openUploader(user_id, post_id)
{
	var url = webroot + 'posts/uploader/' + user_id + '/' + post_id;
	var w = 670, h = 340, l, t;
	var l = (screen.width - w) / 2;
	var t = (screen.height - h) / 2;
	var win = window.open(url, 'uploader', 
				'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,' +
				'width=' + w + ',height=' + h + ',left=' + l + ',top=' + t);
	if (!win) {
		alert("Could not open a new window. Please allow popup window for this site.");
	} else {
		win.resizeTo(w, h);
		win.moveTo(l, t);
		win.focus();
	}
}

//current selected photo's index
var gCurrentPhotoIndex = -1;
var deletedPhotos = [];
var thumbs = [];

function showCaption(photo_index)
{
	if (gCurrentPhotoIndex > 0) {
		$('photo_'+gCurrentPhotoIndex).removeClassName('selected');
		$('caption_'+gCurrentPhotoIndex).hide();		
	}
	$('photo_'+photo_index).addClassName('selected');
	$('caption_'+photo_index).show();		
	gCurrentPhotoIndex = photo_index;
	var number = thumbs.indexOf(photo_index)+1;
	$('photo_number').update(number + '/' + thumbs.length);

	if ($('scroller-wrap').visible())
		scroller.moveToElement($('photo_'+photo_index));
}

function showCaptionIcon(photo_index)
{
	var icon = 'caption_icon_'+photo_index;

	if (!$(icon)) return false;
	if ($('caption_'+photo_index) && $F('caption_'+photo_index)) {
		$(icon).addClassName('caption_icon_filled');
	} else {
		$(icon).removeClassName('caption_icon_filled');
	}
}

function initSortable()
{	
	Sortable.create('sortable_photos', {tag:'div', constraint:false, overlap:'horizontal',
		onUpdate:function() {
			forms_changed = true;
		}});
}

//image controls for add/edit post step 3
var imageControls = {
	currentId: null,
	previousId: null,	
	nextId: null,
	firstId: null,
	lastId: null,
	init: function() {
		this.currentId = gCurrentPhotoIndex;
		var idSequence = Sortable.sequence('sortable_photos');
		idSequence = idSequence.without(deletedPhotos.toString());
		this.firstId = idSequence.first();
		this.lastId = idSequence.last();
		var currentIndex = idSequence.indexOf(this.currentId);
		this.previousId = idSequence[currentIndex-1];
		this.nextId = idSequence[currentIndex+1];
	},
	previous: function() {
		this.init();
		var preId = null;		
		if(this.currentId == this.firstId)
			preId = this.lastId;
		else {
		 	preId = this.previousId;	
		}
		showCaption(preId);
	},
	next: function() {
		this.init();
		var nextId = null;		
		if(this.currentId == this.lastId)
			nextId = this.firstId;
		else {
		 	nextId = this.nextId;	
		}
		showCaption(nextId);
	},
	del: function() {
		if(confirm('Are you sure, you want to delete this photo ? '))
		{
			this.init();
			$("caption_"+this.currentId).value = "";
			$('photo_' + this.currentId).hide();
			$('photospan_' + this.currentId).hide();
			//deletedPhotos.push(this.currentId);
			var URL = webroot + "posts/delete_photo/" + this.currentId;
			new Ajax.Request(URL);
			this.next();
		}
	}
};

function cancelEdit()
{
	if (!confirm('Are you sure you want to cancel? You will lose all of your changes.')) return;
	try {
		$('post-form').reset();
		$('step1-form').reset();
		$('step2-form').reset();
	} catch(e) {
		// alert(e);
	}
	slideUp();
	newPhotos = true;
	new Ajax.Request(webroot+'posts/cancel/'+post_id);
}

var viewContent = '';
function slideUp()
{
	new Effect.SlideUp('editpost', {
		duration: 1,
		beforeStart: function() {
			//remove the preview message
			$('preview_message').hide();
			
			//swap the cancel with the edit post tab again
			$('edit_slide_down').show();
			$('edit_cancel').hide();
			if (isFlash()) {
				// Flash.removeAll();
				$('uploader_div').hide();
			}	
			cancel = true;		
			selectStep(1);
			$('PostBody').value = $F('PostOldbody');
			//clean the destiantion select box area
			Element.update('destinations', '');		
		},
		afterFinish: function() {
			//hide the preview
			Element.hide('preview-container');
			Element.update('preview-container', '');
						
			//show the previous post, since nothing changed
			Element.show('view-container');
			Element.update('view-container', viewContent);
			
			forms_changed = false;
			if (multi_selector)
				multi_selector.removeAll();	
			// SlideShow.initPosition();
			if ($('photos')) {
				SlideShow.init();
				SlideShow.show();
			}
			//$('loading-photos').hide();
		}
	});
}

var viewContent = '';
function slideDown()
{
	new Effect.SlideDown('editpost', {
		duration: 1,
		beforeStart: function() {
			if (isFlash())
				$('uploader_div').hide();
			if ($('slide-prev')) {
				$('slide-prev').hide();
				$('slide-next').hide();
			}
		},
		afterFinish: function() {			
			if (isFlash())
				$('uploader_div').show();
			cancel = false;

			//generate destination select boxes
			DestRows.rows = [];
			DestRows.idCreator.seq = 0;		
			activateDest();			
			
			//save the content of the current post view to e shown again if no changes made			
			if (!viewContent)
				viewContent = $('view-container').innerHTML;
			
			//swap the edit post tab with cancel
			$('edit_slide_down').hide();
			$('edit_cancel').show();
			
			//show the preview message
			$('preview_message').show();
			
			//to detect if changes are made, to know when or when not to load the preview
			handleChanges();
			
			//restart the slideshow, to change the position of the next/previous button
			if ($('photos')) {
				SlideShow.initPosition();
				SlideShow.show();
			}
		}	
	});
	// new Ajax.Request(webroot+'/posts/get_lock/'+post_id);
}

var IdCreator = Class.create();
Object.extend(IdCreator.prototype, {
	seq: 0,

	initialize: function(prefix, idKeys) {
		this.prefix = prefix || 'id';
		this.idKeys = idKeys || [];
	},

	getId: function() {	//create a new id
		return ++this.seq;
	},

	getPrefix: function(key) {
		return this.prefix + '_' + key + '_';
	},

	getRealId: function(id) {
		var realId = '';

		this.idKeys.each((function (v) {
			var prefix = this.getPrefix(v);
			if (id.indexOf(prefix) != -1)
				realId = id.replace(prefix, '');
		}).bind(this));
		return realId;
	},

	getIds: function(id) {
		var h = $H();

		this.idKeys.each((function (v) {
			h[v] = this.getPrefix(v) + id;
		}).bind(this));
		return h;
	}
});

var DestRows = {
	countries: $H(),
	states: $H(),
	// countryWithState: [24, 66],
	containerId : 'destinations',
	idCreator: new IdCreator(this.containerId, ['row', 'country', 'state', 'place', 'add', 'del']),
	rows: [],
	rowLimit: 5,
	
	getHtml: function(rowId) {
		var html, ids;

		ids   = this.idCreator.getIds(rowId);
		html  = '<select class="country" name="data[Destination][country][' + rowId + ']' + '" id="' + ids.country + '" onchange="DestRows.changeCountry(' + rowId + ', this.value)">';
		html += '<option value=""></option>';
		html += this.countries.map(function(v) { return '<option value="' + v.key + '">' + v.value + '</option>'; }).join('');
		html += '</select>';
		html += '<input class="place" type="text" name="data[Destination][place][' + rowId + ']" id="' + ids.place + '" value=""/>';	
		
		return html;
	},
	
	hasState: function(countryId) {
		// console.log(this.states.keys());
		return (this.states.keys().indexOf(countryId) != -1);
	},
	
	changeCountry: function(rowId, value, selected) {
		var ids, html;
		ids = this.idCreator.getIds(rowId);
		if ($(ids.state))
			Element.remove(ids.state);
		if (this.hasState(value)) {
			var states = this.states[value];
			// console.log(states.inspect());
			html  = '<select class="state" name="data[Destination][state][' + rowId + ']" id="' + ids.state + '">';
			html += '<option value=""></option>';
			html += states.map(function(v) { 
				h = '<option value="' + v.key + '"';
				if (selected == v.key)
					h += ' selected="selected"';
				h += '>' + v.value + '</option>';
				return h; 
			}).join('');
			html += '</select>';
			new Insertion.After(ids.country, html);
		}
	},
	
	add: function(beforeRowId) {
		var html, id, ids;
		
		if (this.rows.length >= this.rowLimit) return false;
		
		id	 = this.idCreator.getId();
		ids  = this.idCreator.getIds(id);
		html = this.getHtml(id);
		html = 	'<div class="destination_rows" id="' + ids.row + '">' + html +
				'	<img src="'+webroot+'img/icn_sub.gif" id="' + ids.del + '" alt="remove" width="14" height="14" />' +
				'	<img src="'+webroot+'img/icn_add.gif" id="' + ids.add + '" alt="add" width="14" height="14" />' +
				'</div>';
		if (!beforeRowId) {	//the first one
			new Insertion.Top(this.containerId, html);
		} else {
			var beforeRowIds = this.idCreator.getIds(beforeRowId);
			new Insertion.After(beforeRowIds.row, html);
		}	//end if
		Event.observe( ids.del, 'click', (function() { this.del(id); }).bind(this) );
		Event.observe( ids.add, 'click', (function() { this.add(id); }).bind(this) );
		
		this.rows.push(id);
		this.check();
		handleChanges();
		return id;
	},
	
	del: function(id) {
		var ids = this.idCreator.getIds(id);
		Element.remove(ids.row);
		this.rows = this.rows.inject([], function(h, v) {
			if (v != id) h.push(v);
			return h;
		});
		this.check();
		window.forms_changed = true;
		handleChanges();
	},

	check: function() {
		var id  = this.rows.first();
		var ids = this.idCreator.getIds(id);
		if (this.rows.length == 1) {
			Element.hide(ids.del);
		} else {
			Element.show(ids.del);
		}	//end if
		var len = this.rows.length;
		var last_id = this.rows.last();
		this.rows.each(function(id) {
			var ids = this.idCreator.getIds(id);
			if (len == this.rowLimit || id != last_id) {
				Element.hide(ids.add);
			} else {
				Element.show(ids.add);
			}
		}.bind(this));
	}	
	
};

var scroller = {
	slider: null,
	direction: 'up',
	init: function() {
		var slider = new Control.Slider('handle', 'scroller', {
				axis: 'vertical',
				onSlide: function(v) { scroller.scrollVertical(v);  },
				onChange: function(v) { scroller.scrollVertical(v); }
			});	
		this.slider = slider;
		this.element = $('sortable_photos');
	},
	scrollVertical: function(value){
		this.element.scrollTop = Math.round(value/this.slider.maximum*(this.element.scrollHeight-this.element.offsetHeight));	
	},
	scrollTo: function(value)
	{
		this.scrollVertical(value);
		this.slider.setValue(value, 0);
	},
	up: function() {
		if(this.slider.value>0) {
			this.scrollTo(this.slider.value-0.3);
		}	
	},
	down: function(event) {
		if(this.slider.value<1) {
			this.scrollTo(this.slider.value+0.3);
		}
	},
	moveToElement: function(element) {
		var offsets, elementTop, scrollTop, containerTop, realTop, value;

		offsets = Position.cumulativeOffset(element);
		elementTop = offsets[1];
		offsets = Position.cumulativeOffset($('sortable_photos'));
		containerTop = offsets[1];
		scrollTop = $('sortable_photos').scrollTop;
		realTop = elementTop - scrollTop - containerTop;
		value = this.slider.translateToValue(realTop);
		if (realTop < 0 || realTop > 136) {	//	68/row
			this.scrollTo(value);
		}
	}
};

var first_time = false;

var preview = {
	prevewContainer: 'preview-container',
	before: function() {
		if (!checkStep1()) return false;
		copyStep1FormFields();
		updatePostBody();
		try {
			$("sorting_input").value = Sortable.serialize("sortable_photos");
			$("deleted_input").value = deleted_photos;
		} catch(e) {
			// alert(e);	//We need to check this error later.
		}
		return true;
	},
	show: function(nocheck, noscroll) {
		if (!this.before()) return false;

		if (!$('preview_message').visible())
			$('preview_message').show();

		//if(typeof(window.forms_changed) == "undefined") window.forms_changed = true;
		if(!window.forms_changed && !nocheck) return;
		window.forms_changed = false; //Reset for next step.
		if (noscroll == undefined) {
			noscroll = false;
		}
		if ($('view-container')) {
			this.prevewContainer = 'view-container';
		}

		new Ajax.Updater(this.prevewContainer, webroot+'posts/preview', {
			asynchronous:true, 
			evalScripts:true,
			onComplete:function(request){
				this.after(noscroll);
			}.bind(this),
			parameters:Form.serialize("post-form"),
			requestHeaders:['X-Update', this.prevewContainer]
		}, false);
	},
	after: function(noscroll) {
		$(this.prevewContainer).show();
		if (!noscroll)
			Element.scrollTo('edit-controls');
	}
};

//when the post is being edited >>
function openEdit()
{
	if (isWiki) {
		$('edit_slide_down').hide();
		$('checking-lock').show();
		new Ajax.Updater('lock', webroot+'posts/get_lock/'+post_id, 
			{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'lock']});
	} else {
		slideDown();
	}
}

function setLock(lock)
{
	$('checking-lock').hide();
	$('edit_cancel').show();
	locked = lock;
	if (locked) {	//has been locked by another user
		new Effect.SlideDown('no-edit', {
			duration: 0.1
		});
	} else { //editable
		slideDown();
	}
}

function closeEdit()
{
	if (isWiki && locked) {
		new Effect.SlideUp('no-edit', {
			duration: 0.1,
			afterFinish: function() {
				$('edit_slide_down').show();
				$('edit_cancel').hide();
			}
		});	
	} else {
		cancelEdit();
	}	
}

var upload_completed = false;
function MultiPowUpload_onCompleteAbsolute(type, uploadedBytes)
{
	forms_changed = true;
	upload_completed = true;
	newPhotos = true;
	if ([1,4,5].indexOf(targetStep) != -1) {
		selectStep(targetStep);
		targetStep = 0;
	} else {
		toStep3();
	}
}

function MultiPowUpload_onSelect()
{
	upload_completed = false;
}

// function MultiPowUpload_onComplete(type, fileIndex)
// {
// 	alert(fileIndex);
// 	var files = Flash.fileList();
// 	if (files.indexOf(fileIndex) != -1) 
// 		Flash.removeItemAt(fileIndex);
// 		 		var files = Flash.fileList();
// 		alert($H(files).inspect());
// 	window.alert(type + " of file " + Flash.fileList()[fileIndex].name + " completed successfully.");
// }

function MultiPowUpload_onError(error)
{
	window.alert(error);
}

/**
 * Auto upload the selected files when user click next step.
 * @return boolean Return true if need to upload files, else return false.
 */
function uploadSelectedFiles()
{
	var upload = false; var files;
	try {
		var files = Flash.fileList();
		if (files && files.length > 0 && !upload_completed) {
			Flash.uploadAll();
			return true;			
		}			
	} catch (e) {
		// alert('Exception: '+e);
	}
	return false;
}
// 
// function openFlickrWindow()
// {
// 	var url = webroot + 'pages/flickr';
// 	var w = 670, h = 340, l, t;
// 	var l = (screen.width - w) / 2;
// 	var t = (screen.height - h) / 2;
//      
// 	
// 	var win = window.open(url + '?post_id=' + post_id + '&user_id=' + user_id, 'uploader', 			    
//              'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=no,copyhistory=yes,' +
// 				'width=' + w + ',height=' + h + ',left=' + l + ',top=' + t);
// 
// 	if (!win) {
// 		alert("Could not open a new window. Please allow popup window for this site.");
// 	} else {
// 		win.resizeTo(w, h);
// 		win.moveTo(l, t);
// 		win.focus();
// 	}
// }
