var prefs;
var drag = new _IG_Drag();
var items;
var categories;
var order;
var hash;
var GADGET_TEXTS;

_IG_RegisterOnloadHandler(
	function() {
		prefs = new _IG_Prefs();
		items = JSON.parse(itemsstring);
		categories = JSON.parse(categoriesstring);
		for (var i in items) {
			items[i]['selected'] = false;
		}
		
		if (prefs.getString('order').length >= 1) {
			order = JSON.parse(prefs.getString('order'));
		}
		else {
			order = JSON.parse(ordersstring);
		}
		for (var i in order) {
			items[order[i]]['selected'] = true;
		}
		if (prefs.getString('hash').length != 32) {
			prefs.set('hash', hashstring);
		}
		hash = prefs.getString('hash');
		if (prefs.getString('title').length >= 1) {
			_IG_SetTitle(prefs.getString('title'));
		}
		GADGET_TEXTS = JSON.parse(GADGET_TEXTSstring);

		showItems();
	}
);

function openBox(html) {
	_gel('box').style.display = 'block';
	_gel('box').innerHTML = html;
	
	_gel('closebutton').style.display = 'block';
	
	// make gadget high enough
	_IG_AdjustIFrameHeight();
}

function closeBox() {
	_gel('box').style.display = 'none';
	_gel('box').innerHTML = '';
	
	_gel('closebutton').style.display = 'none';
	
	// make gadget high enough
	_IG_AdjustIFrameHeight();
}

function removeAmpersands(value) {
	var ampersand = '&amp;';
	ampersand = ampersand.substr(0, 1);
	while (value.indexOf('&amp;') != -1) {
		value = value.replace('&amp;', ampersand);
	}
	return value;
}

function saveItems() {
	prefs.set('order', JSON.stringify(order));
}

function showItems() {
	// remove all existing drag items
	drag.removeAllSources();
	
	// show items
	var html = '';
	for (var i in order) {
		html += '<div id="item_' + i + '">';
		html += '<img src="' + GADGET_URL + '/icons/' + order[i] + '.' + items[order[i]]['extension'] + '" border="0" alt="' + items[order[i]]['name'].replace('\'', '\\\'') + '" title="' + items[order[i]]['name'].replace('\'', '\\\'') + '"/><br/>';
		html += '</div>';
	}
	_gel('items').innerHTML = html;
	
	// add items to drag object
	for (var i in order) {
		drag.addSource('item_' + i);
		drag.addTarget('item_' + i);
	}
	
	// make gadget high enough
	_IG_AdjustIFrameHeight();
}

function addItem(i) {
	closeBox();
	
	i = '' + i;
	if (i.length != 0) {
		if (items[i]['selected']) {
			window.alert(GADGET_TEXTS['item_exists']);
			return;
		}
		items[i]['selected'] = true;
		order[order.length] = i;
		saveItems();
		showItems();
	}
}

function showAddItem(category) {
	if (category == '') {
		category = null;
	}
	var html = '<h6>' + GADGET_TEXTS['title_search_item'] + '</h6>';
	html += '<input type="text" id="box_pattern"/><br/>';
	html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_search_item'] + '" onclick="searchItem(_gel(\'box_pattern\').value)"/><br/><br/>';
	html += '<h6>' + GADGET_TEXTS['title_add_item'] + '</h6>';
	html += '<select id="box_category" onchange="showAddItem(_gel(\'box_category\').options[_gel(\'box_category\').selectedIndex].value)">';
	if (category == null) {
		html += '<option value="" selected="selected">- ' + GADGET_TEXTS['select_category'] + ' -</option>';
	}
	else {
		html += '<option value="">- ' + GADGET_TEXTS['select_category'] + ' -</option>';
	}
	for (var i in categories) {
		if (categories[i]['name'] == '') {
			continue;
		}
		if (category == i) {
			html += '<option value="' + i + '" selected="selected">' + categories[i]['name'] + '</option>';
		}
		else {
			html += '<option value="' + i + '">' + categories[i]['name'] + '</option>';
		}
	}
	html += '</select><br/>';
	html += '<select id="box_item">';
	if (category != null) {
		html += '<option value="" selected="selected">- ' + GADGET_TEXTS['select_item'] + ' -</option>';
		for (var i in categories[category]['items']) {
			if (!items[categories[category]['items'][i]]['selected']) {
				html += '<option value="' + categories[category]['items'][i] + '">' + items[categories[category]['items'][i]]['name'] + '</option>';
			}
		}
	}
	else {
		html += '<option value="" selected="selected">- ' + GADGET_TEXTS['select_category_first'] + ' -</option>';
	}
	html += '</select><br/>';
	html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_add_item'] + '" onclick="addItem(_gel(\'box_item\').options[_gel(\'box_item\').selectedIndex].value)"/>';
	html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_link_request'] + '" onclick="showContact()"/>';
	
	openBox(html);
}

function searchItem(pattern) {
	if (pattern.length == 0) {
		closeBox();
		return;
	}
	
	var results = new Array();
	for (var i in categories) {
		for (var j in categories[i]['items']) {
			if ((items[categories[i]['items'][j]]['name'].toLowerCase().indexOf(pattern.toLowerCase()) != -1)
			 || (items[categories[i]['items'][j]]['url'].toLowerCase().indexOf(pattern.toLowerCase()) != -1)) {
				results[results.length] = categories[i]['items'][j];
			}
		}
	}

	var html = '<h6>' + GADGET_TEXTS['title_search_item'] + '</h6>';
	html += '<input type="text" id="box_pattern" value="' + pattern.replace('"', '\\\'\\\'') + '"/><br/>';
	html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_search_item'] + '" onclick="searchItem(_gel(\'box_pattern\').value)"/><br/><br/>';
	if (results.length > 0) {
		html += '<h6>' + GADGET_TEXTS['title_search_item_results'] + '</h6>';
		html += '<ul class="searchItem">';
		for (var i in results) {
			if (i % 2 == 1) {
				html += '<li class="even" onclick="addItem(' + results[i] + ')"><a href="#" onclick="addItem(' + results[i] + ')" class="action">+</a><a href="#" onclick="addItem(' + results[i] + ')">' + items[results[i]]['name'] + '</a></li>';
			}
			else {
				html += '<li class="odd" onclick="addItem(' + results[i] + ')"><a href="#" onclick="addItem(' + results[i] + ')" class="action">+</a><a href="#" onclick="addItem(' + results[i] + ')">' + items[results[i]]['name'] + '</a></li>';
			}
		}
		html += '</ul><br/>';
		html += '<h6>' + GADGET_TEXTS['title_add_item'] + '</h6>';
		html += '<select id="box_category" onchange="showAddItem(_gel(\'box_category\').options[_gel(\'box_category\').selectedIndex].value)">';
		html += '<option value="" selected="selected">- ' + GADGET_TEXTS['select_category'] + ' -</option>';
		for (var i in categories) {
			if (categories[i]['name'] == '') {
				continue;
			}
			html += '<option value="' + i + '">' + categories[i]['name'] + '</option>';
		}
		html += '</select><br/>';
		html += '<select id="box_item">';
		html += '<option value="" selected="selected">- ' + GADGET_TEXTS['select_category_first'] + ' -</option>';
		html += '</select><br/>';
		html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_add_item'] + '" onclick="addItem(_gel(\'box_item\').options[_gel(\'box_item\').selectedIndex].value)"/>';
		html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_link_request'] + '" onclick="showContact()"/>';
	}
	else {
		html += '<h6>' + GADGET_TEXTS['title_search_item_no_results'] + '</h6>';
		html += GADGET_TEXTS['label_contact_sender'] + '<br/>';
		html += '<input type="text" id="box_sender"/><br/>';
		html += GADGET_TEXTS['label_contact_comment'] + '<br/>';
		html += '<textarea id="box_comment">' + GADGET_TEXTS['link_request_comment'].replace('%1%', pattern) + '</textarea><br/>';
		html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_send'] + '" onclick="contact(_gel(\'box_sender\').value, _gel(\'box_comment\').value)"/>';
	}
	
	openBox(html);
}

function removeItem(i) {
	closeBox();
	
	i = '' + i;
	if (i.length != 0) {
		items[order[i]]['selected'] = false;
		order.splice(i, 1);
		saveItems();
		showItems();
	}
}

function showRemoveItem() {
	var html = '<h6>' + GADGET_TEXTS['title_remove_item'] + '</h6>';
	html += '<ul class="removeItem">';
	for (var i in order) {
		if (items[order[i]]['selected']) {
			if (i % 2 == 1) {
				html += '<li class="even" onclick="removeItem(' + i + ')"><a href="#" onclick="removeItem(' + i + ')" class="action">X</a><a href="#" onclick="removeItem(' + i + ')">' + items[order[i]]['name'] + '</a></li>';
			}
			else {
				html += '<li class="odd" onclick="removeItem(' + i + ')"><a href="#" onclick="removeItem(' + i + ')" class="action">X</a><a href="#" onclick="removeItem(' + i + ')">' + items[order[i]]['name'] + '</a></li>';
			}
		}
	}
	html += '</ul>';
	
	openBox(html);
}

function contact(sender, comment) {
	closeBox();
	
	comment = '' + comment;
	while (comment.indexOf('\n') != -1) {
		comment = comment.replace('\n', ' ');
	}
	if (comment.length != 0) {
		if (sender == '') {
			var url = GADGETS_URL + '/mail.dll?hash=' + hash + '&language=' + GADGET_LANGUAGE.toLowerCase() + '&version=' + GADGET_VERSION + '&comment=' + escape(comment);
		}
		else {
			var url = GADGETS_URL + '/mail.dll?hash=' + hash + '&language=' + GADGET_LANGUAGE.toLowerCase() + '&version=' + GADGET_VERSION + '&sender=' + escape(sender) + '&comment=' + escape(comment);
		}
		_IG_FetchContent(url, function (responseText) {
				if (responseText == 'Mail sent.') {
					window.alert(GADGET_TEXTS['mail_sent']);
				}
				else {
					window.alert(GADGET_TEXTS['mail_error'] + responseText);
				}
		});
	}
}

function showContact() {
	var html = '<h6>' + GADGET_TEXTS['title_contact'] + '</h6>';
	html += GADGET_TEXTS['label_contact_sender'] + '<br/>';
	html += '<input type="text" id="box_sender"/><br/>';
	html += GADGET_TEXTS['label_contact_comment'] + '<br/>';
	html += '<textarea id="box_comment"></textarea><br/>';
	html += '<input type="button" class="button" value="' + GADGET_TEXTS['button_send'] + '" onclick="contact(_gel(\'box_sender\').value, _gel(\'box_comment\').value)"/>';
	
	openBox(html);
}

drag.onDragEnd = function(source, target) {
	if (target == null) return;
	
	var source_index = parseInt(source.id.replace('item_', ''));
	var target_index = parseInt(target.id.replace('item_', ''));
	
	var temp = order[source_index];
	if (source_index > target_index) {
		for (var i = source_index - 1; i >= target_index; i--) {
			order[i + 1] = order[i];
		}
	}
	else {
		for (var i = source_index + 1; i <= target_index; i++) {
			order[i - 1] = order[i];
		}
	}
	order[target_index] = temp;
	
	saveItems();
	showItems();
}

drag.onDragClick = function(source) {
	var source_index = parseInt(source.id.replace('item_', ''));
	window.open(items[order[source_index]]['url'], '_blank');
}