/*!
*	Copyright (c) 2007 Bethke et al. GmbH, Berlin, Germany copyright@b-et-a.de
* All rights reserved.
* Authors:
*   Ingo Struck - seen at ingostruck dot de
*   Mathias Schaefer - mathias.schaefer at 9elements dot com
*/

/*
Table of Contents:
- SEEN
- SWF Functions
- flash Object
- Search Object
- formStatus Object
- Initialize onReady

*/


/* *************************************************** SEEN *************************************************** */

// start seen
var seen = {

	// Assumed width of the vertical scrollbar on the right side of the viewport
	scrollbarWidth : 18,
	hd_timo : 5000,
	
	onReady: function () {

		// Set body class
		document.body.className = 'javascript-enabled';
		
		util.populateInput();
		
		// Set base view
		seen.baseView = false;
		var viewNavigation = $('viewNavi');
		if (viewNavigation) {
			var matches = viewNavigation.className.match(/^view(\d+)$/);
			if (matches && matches[1]) {
				seen.baseView = matches[1];
			}
		}
		// Workaround for the single image views:
		// if the image is clicked, just call history.back()
		if (seen.baseView == 90 || seen.baseView == 91) {
			$('pageImg').onclick = function (evt) {
				// Prevent default
				util.uni_event(evt);
				history.back();
			};
		}

		// swap headlines
		var tswap = $('tswap');
		if (tswap) {
			var lst = tswap.getElementsByTagName('li');
			if ( 1 < lst.length) {
				seen.hd_act = 0;
				seen.hd_cnt = lst.length;
				seen.hd_lst = lst;
				seen.hd_swap = function () {
					var tswap = $('tswap');
					var lst = tswap.getElementsByTagName('li');
					lst[seen.hd_act].className = 'hidden';	
					++seen.hd_act;
					if (seen.hd_cnt <= seen.hd_act) seen.hd_act = 0;
					lst[seen.hd_act].className = '';
				};
				seen.hd_ivl = setInterval( seen.hd_swap, seen.hd_timo );
			}
		} // if tswap

		// back link
		var ovwln = $('back_ctx');
		if (ovwln) {
			ovwln.href = 'javascript:back();';
		}
	}
	
};
// end seen

/* *************************************************** SEARCH *************************************************** */

// start search
function Search (options) {
	if (!options || !options.input || !options.subdomain) {
		return;
	}
	this.input = options.input;
	this.subdomain = options.subdomain;
	this.onlyOneTerm = typeof(options.onlyOneTerm) == 'boolean' ? options.onlyOneTerm : false;
	this.submitAfterComplete = typeof(options.submitAfterComplete) == 'boolean' ? options.submitAfterComplete : false;
	this.onsubmit = typeof(options.onsubmit) == 'function' ? options.onsubmit : false;
	this.init();
}

Search.prototype = {

	/* Properties */
	
	timeout : false,
	
	// div element where the results appear
	resultBox : false,
	
	tokenList : [],
	
	termCompletion : false,
	
	operators : [
		'+',
		'-'
	],

	/* Methods */
	
	init : function () {
		this.input.autocomplete = 'off';
		this.input.showInfo = true;
		this.input.value = "";
		this.input.onkeyup = this.keyup.bindAsEventListener(this);
		this.input.onkeydown = this.stopTimeout.bindAsEventListener(this);
		this.input.onfocus = this.input_onFocus.bindAsEventListener(this);
		this.input.onblur = this.input_onBlur.bindAsEventListener(this);
		if (this.onsubmit) {
			this.input.form.onsubmit = this.onsubmit.bindAsEventListener(this);
		}
	},

	keyup : function (evt) {
		evt = util.uni_event(evt, true);
		
		switch (evt.which) {
			case 37: // cursor keys
			case 38:
			case 39:
			case 40:
				break;
			case 8: // backspace
			case 46: // delete
				if (this.removeTerm()) {
					evt.preventDefault();
					evt.stopPropagation();
				}
				break;
			case 13: // enter
				if (this.onsubmit) {
					this.onsubmit();
					evt.preventDefault();
					evt.stopPropagation();
				}
				break;
			default:
				this.stopTimeout();
				this.timeout = setTimeout(this.start.bind(this), 400);
		}
	
	},
	
	stopTimeout : function () {
		if (this.timeout)
			window.clearTimeout(this.timeout);
	},
	
	tokenize : function () {
		this.input.oldValue = this.input.value;

		var value = util.trim(this.input.value);
		var tokenList = [];
		
		// Tokenize
		var tokens = value.split(/\s+/);
		for (var j = 0; j < tokens.length; j++) {
			var token = tokens[j];
			if (token == '') continue;
			if (token.length > 1) {
				var firstCharacter = token.charAt(0);
				if (this.operators.contains(firstCharacter)) {
					tokenList.push(firstCharacter);
					token = token.substring(1);
				}
			}
			tokenList.push(token);
		}
		this.tokenList = tokenList;
		
		return tokenList;

	},
	
	linearize : function (tokenList) {
		var string = '';
		var length = tokenList.length;
		for (var i = 0; i < length; i++) {
			if (tokenList[i] != '') {
				string += tokenList[i];
			}
			if (i < length - 1) {
				string += ' ';
			}
		}
		return string;
	},
	
	replace : function (search, replace, replaceWithOperator) {
		var tokenList = this.tokenList.clone(); // copy, not reference
		var operators = this.operators;
		var replaced = false;
		var searchRegExp = new RegExp('^' + search.replace('.', '\\.') + '$', 'i');

		// Replace last matching token
		for (var i = tokenList.length - 1; i >= 0; i--) {
			if (searchRegExp.test(tokenList[i])) {
				if (!replaceWithOperator) {
					tokenList[i] = replace;
					replaced = true;
					break;
				} else if (operators.contains(tokenList[i - 1])) {
					tokenList[i] = replace;
					tokenList[i - 1] = '';
					replaced = true;
					break;
				}
			}
		}
		if (replaced) {
			this.input.value = this.linearize(tokenList);
		}

		return replaced ? tokenList : false;
	},
	
	removeTerm : function () {
		var diff = this.diff();
		if (!diff) {
			return false;
		}

		return this.replace(diff.token, '', true);
		
	},
	
	diff : function () {
		if (this.input.value == this.input.oldValue) {
			return false;
		}
		
		var oldL = this.tokenList;
		var newL = this.tokenize();
		if (oldL.length == 0 && newL.length == 0) {
			return false;
		}
		
		if (oldL.length == 0) {
			return { number : 0, token : newL[0] };
		}
		
		var changed = false;
		var length = Math.max(oldL.length, newL.length);
		for (var i = 0; i < length; i++) {
			if (oldL[i] != newL[i] && !this.operators.contains(newL[i])) {
				changed = true;
				break;
			}
		}
		if (!changed) {
			return false;
		}
		
		
		var changedToken = newL[i] == undefined ? '' : newL[i];
		
		return { number : i, token : changedToken };
		
	},
	
	start : function () {
		var diff = this.diff();
		if (diff) {
			if (this.onlyOneTerm && diff.number != 0) {
				return;
			}
			var data = diff.token;
			if (!data) {
				return;
			}
			this.termCompletion = data;
			channel.send(this.subdomain, '/' + data.toLowerCase(), 'GET', this.handleResponse.bind(this), false);
		}

	},
	
	complete : function (completeTerm, closeResultBox) {
		var imcompleteTerm = this.termCompletion;
		if (imcompleteTerm == completeTerm) {
		} else {
			this.replace(imcompleteTerm, completeTerm, false);
			this.input.focus();
		}
		
		if (closeResultBox && this.resultBox)
			dynDiv.del(this.resultBox);
		
		return false;
	},
	
	handleResponse : function (res, status, headers) {
		if (status != 200 || !res || res.length == 0) {
			if (this.resultBox) {
				dynDiv.del(this.resultBox);
			}
			return;
		}
		
		var lines = res.split('\n');
		for (var i = 0; i < lines.length; i++) {
			lines[i] = lines[i].split('\t');
		}
		var linesLength = lines.length - 1;

		if (linesLength == 0) {
			return;
		}

		var firstLine = lines[0];

		if (linesLength == 1 && firstLine[0] != '') {
			this.complete(firstLine[0], true);
			if (this.submitAfterComplete)
				this.onsubmit();
			return;
		}
		var ulElem = document.createElement('ul');

		//var commonPrefix = lines[0][0];
		
		for (var i = 0; i < linesLength; ++i ) {
			var line = lines[i], term = line[0], number = line[1];
			
			/*
			// Find new common prefix
			var plen = Math.min(term.length, commonPrefix.length);
			for (var nlen = 0; nlen < plen; ++nlen)
				if (term.charCodeAt(nlen) != commonPrefix.charCodeAt(nlen))
					break;
			commonPrefix = commonPrefix.substring(0, nlen);
			*/
			
			var liElem = document.createElement('li');
			ulElem.appendChild(liElem);
			
			var aElem = document.createElement('a');
			liElem.appendChild(aElem);
			aElem.href = '#';
			// Save a reference to the Search instance at the anchor element
			aElem.searchInstance = this;
			aElem.completeTerm = term;
			aElem.onclick = function (evt) {
				// Reminder: 'this' points to the clicked anchor,
				// 'this.searchInstance' to the corresponding instance object
				evt = util.uni_event(evt);
				this.searchInstance.complete(this.completeTerm, true);
				if (this.searchInstance.submitAfterComplete)
					this.searchInstance.onsubmit();
			};
			var textnode = document.createTextNode(term + ' (' + number + ')');
			aElem.appendChild(textnode);
			
		}
		var offset = util.off_elem(this.input);
		var left = offset[0];
		var top = offset[1] + this.input.offsetHeight;
		
		var resultBox = dynDiv.add(
			'search_results',
			left, top,		// left/top
			350, 300,		// width/height
			100,				// z-index base
			false,			// parent (false == document.body)
			0				// header height
		);
		this.resultBox = resultBox;

		resultBox._content.innerHTML = '';
		resultBox._content.appendChild(ulElem);

		resultBox.show();
	},

	input_onFocus : function (evt) {
		this.input.oldValue = this.input.value;
		/* DOSE NOT WORK, because of broken structure for sel
		this.input.value = '';
		*/
		this.input.showInfo = false;
	},

	input_onBlur : function (evt) {
		if ('undefined' != typeof(this.input.oldValue)) this.input.value = this.input.oldValue;
		this.input.showInfo = true;
		/* DOES NOT WORK, because of broken structure for sel
		//this.stopTimeout();
		if (this.resultBox) {
			//dynDiv.del(this.resultBox);
		}
		*/
	}

}; // Search.prototype

Search.onReady = function () {

	/* Init main search */
	var form = $('srch_frm'), input = $('full');
	if (form && input) {
		form.autocomplete = 'off';

		// focus search field only if it's visible, otherwise it throws an exception in IE
		if (input.value == '' && '' == location.hash && util.getStyle($('contHead'), 'display') == 'block') {
			input.focus();
		}
	}
	
	/* Init location autocomplete */
	/*
	if ($('form_register') || $('form_profile')) {
		var input = $('pl') || $('pl0');
		if (!input) return;
		new Search(
			{
				input : input,
				subdomain : 'loc.incr',
				onlyOneTerm : true,
				submitAfterComplete : false
			}
		);
	}
	*/
};
// end search

/* *************************************************** FORM STATUS  *************************************************** */

// start formStatus
var formStatus = {
	
	/* Properties */
	
	titleInput: 'ttl', // imagetitle inputfield
	
	statusMessageId: 'status_message',
	requiredSrc: '/css/skin' + util.skin + '/field_required.png',
	filledSrc: '/css/skin' + util.skin + '/field_required.png',
	missingSrc: '/css/skin' + util.skin + '/field_required.png',

	/* Methods */

	onReady : function () {
		var wrapperElement = $('form_profile');
		if (!wrapperElement) return;
		
		var formList = wrapperElement.getElementsByTagName('form');
		if (!formList.length) return;
		
		var editForm = formList[0];
		
		formStatus.message(); // create status message
		
		// collect checkboxes
		var editForm = document.forms[0]; // todo: get form by id or name
		var inputs = editForm.getElementsByTagName('input');
		formStatus.chkboxes = Array();
		for (var i=0; i<inputs.length; i++) {
			if (inputs[i].type == 'checkbox') {
				// eventhandling checkboxes
				inputs[i].onclick = function () {
					var numValidFields = formStatus.chkSts();
					formStatus.message(numValidFields);
				}
				formStatus.chkboxes.push(inputs[i]);
			}
		}
		
		// eventhandling title-input
		$(formStatus.titleInput).onblur = function () {
			var numValidFields = formStatus.chkSts();
			formStatus.message(numValidFields);
		};
		
		// eventhandling form-submit
		editForm.onsubmit = function () {
			var numValidFields = formStatus.chkSts();
			if (numValidFields < 4) {
				formStatus.message(numValidFields);
				return false;
			} else {
				return true;
			}
		};
	},
	
	message: function (numValidFields) {	
		var bullet = document.createElement('img');
		bullet.src = formStatus.requiredSrc;
		var message = document.createElement('p');
		message.id = formStatus.statusMessageId;
		message.appendChild( document.createTextNode('you filled '+(numValidFields || '0')+' of 4 required (') );
		message.appendChild( bullet );
		message.appendChild( document.createTextNode(') fields.') );
		message.appendChild( document.createTextNode(' Status: ') );
		
		var fldset = document.getElementsByTagName('fieldset')[2];
		var messageEl = $(formStatus.statusMessageId);
		if (messageEl) messageEl.innerHTML = message;
		
	},
	
	chkSts: function () {
		var title = $(formStatus.titleInput); // image title
		var media = 0;
		var type_of_work = 0;
		var genre = 0;
		for (var i=0; i<formStatus.chkboxes.length; i++) {
			if ( /^media/i.test(formStatus.chkboxes[i].name) && formStatus.chkboxes[i].checked ) {
				media++;
			}
			if ( /^type_of_work/i.test(formStatus.chkboxes[i].name) && formStatus.chkboxes[i].checked ) {
				type_of_work++;
			}
			if ( /^genre/i.test(formStatus.chkboxes[i].name) && formStatus.chkboxes[i].checked ) {
				genre++;
			}
		}
		var numValidFields = 0;
		if (title.value != '') numValidFields++;
		if (media > 0) numValidFields++;
		if (type_of_work > 0) numValidFields++;
		if (genre > 0) numValidFields++;
		
		return numValidFields;
	}

};
// end formStatus

/* *************************************************** Initialize onReady *************************************************** */

util.add_event(window, 'load', util.onReady);
util.add_event(window, 'load', channel.onReady);

util.add_event(window, 'load', seen.onReady);

util.add_event(window, 'load', Search.onReady);
//util.add_event(window, 'load', formStatus.onReady);

util.add_event(window, 'load', upload.onReady);

util.add_event(window, 'load', slide.onReady);
util.add_event(window, 'load', band.onReady);
