/*global $ */
var imgid=0;
function language() {
	var lang;
	if(navigator.appName == 'Netscape') {
		lang = navigator.language;
	} else {
		lang = navigator.browserLanguage;
	}
	if(lang.indexOf('de') <= -1) {
		return "en";
	}
	else {
		return "de";
	}
}

var langdata = {"de": {
		"browse": "Durchsuchen...",
		"dragdrop": "Bild hier hinein ziehen",
		"dragdrop_multiple": "gerne auch mehrere :)",
		"dragdrop_limit": "bis zu 10 Grafiken :)",
		"or": "oder",
		"error_keine_datei": "Datei leer.<br/>Bitte wähle eine Datei vom Typ JPG, GIF, PNG, BMP oder PSD.",
		"error_ungueltige_dateiendung": "Falscher Dateityp!<br/>Bitte wähle eine Datei vom Typ JPG, GIF, PNG, BMP oder PSD.",
		"error_ungueltiges_mime": "Falscher Dateityp!<br/>Bitte wähle eine gültige Datei vom Typ JPG, GIF, PNG, BMP oder PSD.",
		"error_too_big": "Datei zu groß!<br/>Dein Bild darf maximal 8 MB groß sein.",
		"error_damaged": "Datei beschädigt!<br/>Dein Bild ist beschädigt und kann leider nicht verarbeitet werden.",
		"error_saving": "Fehler beim Speichern der Datei!<br/>Sorry, bitte versuche es später erneut.",
		"error_imageban": "AGB-Verstoß.<br/>Die ausgewählte Grafik verstößt gegen unsere AGB und darf nicht hochgeladen werden.",
		"error_too_many_files": "Max. 10 Dateien gleichzeitig!<br/>Bitte wähle immer nur 10 Dateien gleichzeitig zum Upload aus."
	},
	"en": {
		"browse": "Browse...",
		"dragdrop": "Drag-n-Drop image file here",
		"dragdrop_multiple": "as many as you like :)",
		"dragdrop_limit": "up to 10 images :)",
		"or": "or",
		"error_keine_datei": "Empty file.<br/>Please upload a JPG, GIF, PNG, BMP or PSD file.",
		"error_ungueltige_dateiendung": "Wrong file!<br/>Please upload a JPG, GIF, PNG, BMP or PSD file.",
		"error_ungueltiges_mime": "Wrong file!<br/>Please upload a valid JPG, GIF, PNG, BMP or PSD file.",
		"error_too_big": "File too big!<br/>Please upload an image file with less than 8 MB.",
		"error_damaged": "File damaged!<br/>The uploaded image file is damaged and cannot be processed.",
		"error_saving": "Error while saving file!<br/>Sorry, please retry later.",
		"error_imageban": "Infringement<br/>The uploaded file violates our rules and must not be uploaded.",
		"error_too_many_files": "Max. 10 files at once!<br/>Please select only 10 files to upload at one go."
	}
};

var combopos = 0;
function konamiInput(evt){
  var combo = new Array(38, 38, 40, 40, 37, 39, 37, 39, 66, 65);
  var e = evt || window.event; 
  if(e.which == combo[combopos] || e.which == undefined && e.keyCode == combo[combopos]) {
    combopos++;
  }
  else {
    combopos = 0;
  }
  
  if(combopos == combo.length) {
    document.getElementById("imgup_logo").src = "img_int/logo_konami.gif?" + Math.round(Math.random()*999999);
    combopos = 0;
  }
  return true;
}

function initKonami(){
  if(document.captureEvents) {
    document.captureEvents(Event.KEYUP);
  }
  document.onkeyup = konamiInput;
}

function i18n(key) {
	return langdata[language()][key];
}

function dragDropSupported() {
	return (typeof FileReader != 'undefined') && ('draggable' in document.createElement('span'));
}

function removeSlowly(selector) {
	$(selector).fadeOut(500, function () {
		$(selector).remove();
	});
}

function showAllLinks(imgid) {
	$('#showlinks-' + imgid).hide(0, function() {
		$('#linktable-' + imgid).animate({height: 'toggle', opacity: 'toggle'}, 500);
	});
	
}

function errorIcon() {
	return "<div style='text-align: center'><img src='img_int/upload_error.gif'/></div>";
}

String.prototype.truncate = function(length) {
	if(this.length > length) {
		return this.substring(0, length) + "...";
	}
	else {
		return this;
	}
}

function inputSelect() {
	$(this).focus();
	$(this).select();
}

$(function () {
	$('#browse_label').html(i18n("browse"));
	$('#upload_drop_label1').html(i18n("dragdrop"));
	$('#upload_drop_label2').html(i18n("dragdrop_multiple"));
	$('#upload_drop_label2_alt').html(i18n("dragdrop_limit"));
	
	if(dragDropSupported()) {
		$('#or_label').html(i18n("or"));
		$('#upload_drop').show();
	}
	
	$('#helplink').hoverIntent({over: function() {
		$('#inline_help').fadeIn(200);
	}, out: function() {
		$('#inline_help').fadeOut(200);
	},
	timeout: 1000});
	
    $('#file_upload').fileUploadUI({
		previewMaxWidth: 120,
		previewMaxHeight: 120,
        uploadTable: $('#files'),
        downloadTable: $('#files'),
		dropZone: $('#upload_drop'),
		url: function (form) {
			return form.attr('action') + "&from=ajax";
		},
		
        buildUploadRow: function (files, index) {
			var imgname = files[index].name.replace(/(c:\\)*fakepath\\/i, '');
            var res = $('<tr><td class="file_upload_preview" style="width: 120px; height: 120px; vertical-align: middle; text-align: right; padding-right: 10px"></td><td style="width: 380px; padding-top: 20px"><table style="width:100%"><tr><td colspan="2" class="upload_title bolded" style="padding-bottom: 5px">Bild ' + imgname.truncate(12) + ' wird hochgeladen...</td></tr>' +
                    '<tr><td class="file_upload_progress" style="width: 100%; padding-top: 7px; padding-right: 10px"><div></div></td>' +
                    '<td class="file_upload_cancel">' +
                    '<button>Abbrechen</button></td></tr></table></td></tr>');
			var hidebtn = res.find(".file_upload_cancel button")
			hidebtn.button({text: false, icons: {primary:'ui-icon-cancel'}});
			return res;
        },
        buildDownloadRow: function (file) {
			var myid = ++imgid;
			var res = "";
			if(file.state != "success") {
				setTimeout(function () {
					removeSlowly("#imgrow" + myid);
				}, 10000);
					res = $('<tr id="imgrow' + myid + '"><td class="icon_area" style="width: 120px;">' + errorIcon() + '</td><td><table style="width:100%"><tr><td class="bolded" colspan="2">Fehler beim Upload:</td></tr><tr><td>' + i18n(file.state) + '</td><td>' +
					'<button class="hidebtn">Ausblenden</button></td></tr></table></td></tr>');
			} else {
				res = $("<tr id='imgrow" + myid + "'><td style='width: 120px'><a href='" + file.img_link + "' target='_blank'><img src='" + file.thumb_link + "' border='0' style='width: 120px; height: 120px'></a></td><td style='width: 380px;'><div style='position:relative;text-align: left'><div class='bolded centered' style='padding-top: 6px;'><a href='" + file.img_link + "' target='_blank' style='font-size: 10pt; padding-right: 30px'>" + file.name.truncate(12) + "  wurde erfolgreich hochgeladen!</a></div>" +
				"<div style='position: absolute; right: 0; top: 0'><button class='hidebtn'>Ausblenden</button></div>" +
				"<form action='#' onsubmit='return false;'>" +
				"<div id='image_link'><div><a href='" + file.img_link + "' target='_blank' class='bolded' style='text-decoration: none; font-size: 8pt;'>Image-Link:</a></div><input type='text' value='" + file.img_link + "' class='textfield linkfield' readonly='readonly'>" +
				"<div id='showlinks-" + myid + "' style='text-align:right;margin-top:4px'><a class='icon' style='color:#666666;font-size:7pt;text-decoration:none' onClick='showAllLinks(\"" + myid + "\")'>Show all links »</a></div></div>" +
"<div id='linktable-" + myid + "' class='hiddenitem'><table class='linktable'>" +
"<tr><td colspan='2' class='bolded'>Weitere Links:</td></tr>" +
"<tr>"+
	"<td style='width: 95px'><a href='" + file.thumb_link + "' target='_blank' style='white-space: nowrap'>Thumbnail-Link</a>:</td>"+
	"<td><input type='text' value='" + file.thumb_link + "' class='textfield linkfield' readonly='readonly'></td>"+
"</tr>"+
"<tr>"+
	"<td><a href='" + file.direct_link + "' target='_blank'>Direct-Link</a>:</td>"+
	"<td><input type='text' value='" + file.direct_link + "' class='textfield linkfield' readonly='readonly'></td>"+
"</tr>"+
"<tr><td colspan='2' class='bolded'>Foren-Code:</td></tr>"+
"<tr><td>Thumbnail:</td>"+
	"<td><input type='text' value='[url=" + file.img_link + "][img]" + file.thumb_link + "[/img][/url]' class='textfield linkfield' readonly='readonly'></td>"+
"</tr>"+
"<tr><td>Vollansicht:</td>"+
	"<td><input type='text' value='[url=http://img-up.net][img]" + file.direct_link + "[/img][/url]' class='textfield linkfield' readonly='readonly'></td>"+
"</tr>"+
"<tr><td colspan='2' class='bolded'>HTML-Code:</td></tr>"+
"<tr><td>Thumbnail:</td>"+
	"<td><input type='text' value='&lt;a href=\"" + file.img_link + "\" target=\"_blank\"&gt;&lt;img src=\"" + file.thumb_link + "\" border=\"0\"&gt;&lt;/a&gt;' class='textfield linkfield' readonly='readonly'></td>"+
"</tr>"+
"<tr><td>Vollansicht:</td>"+
	"<td><input type='text' value='&lt;a href=\"http://img-up.net/\" target=\"_blank\"&gt;&lt;img src=\"" + file.direct_link + "\" border=\"0\"&gt;&lt;/a&gt;' class='textfield linkfield' readonly='readonly'></td>"+
"</tr></table></div></form>"+
"</div></td></tr>");
			}
			var hidebtn = res.find("button.hidebtn")
			hidebtn.button({text: false, icons: {primary:'ui-icon-close'}});
			hidebtn.click(function() {
				removeSlowly('#imgrow' + myid);
			});
			res.find("input.linkfield").click(inputSelect);
			res.find("input.linkfield").bind("mouseover", inputSelect);
			return res;
        },
		beforeSend: function (event, files, index, xhr, handler, callBack) {
			var regexp = /\.(png)|(jpg)|(jpeg)|(gif)|(bmp)|(psd)$/i;
			var err = false;
			if (!regexp.test(files[index].name)) {
				handler.uploadRow.find('.file_upload_progress').html(i18n("error_ungueltige_dateiendung"));
				err = true;
			}
			else if (files[index].size > 8 * 1024 * 1024) {
				handler.uploadRow.find('.file_upload_progress').html(i18n("error_too_big"));
				err = true;
			}
			else if (index > 9) {
				handler.uploadRow.find('.file_upload_progress').html(i18n("error_too_many_files"));
				err = true;
			}
			if(err) {
				handler.uploadRow.find('.upload_title').html("Fehler beim Upload:");
				handler.uploadRow.find('.file_upload_preview').html(errorIcon());
				setTimeout(function () {
					removeSlowly(handler.uploadRow);
				}, 10000);
				return;
			}
			callBack();
		},
		dropZoneEnlarge: function () {
			$('#upload_drop_label2').hide();
			$('#upload_drop_label2_alt').show();
		},
		dropZoneReduce: function () {
			$('#upload_drop_label2').show();
			$('#upload_drop_label2_alt').hide();
		}
    });
	
	initKonami();
});

