BreadCrumbDropDown = {
	init : function() {
		$(".root.header .rootline .link.withOptions").bind("mouseenter", function() {
			var clone = $(this).clone();
			var offset = $(this).offset();
			clone.addClass("active");
			clone.css("left", offset.left-1);
			clone.css("top", offset.top-1);
			clone.bind("mouseleave", function() {
				$(this).remove();
			});
			clone.insertAfter(this);
		});
	}
};

function InitSearchBox(text) {
	var input = $("#search_input");
	var button = $("#search_button");
	
	input.attr("value", text);
	input.addClass("empty");
	input.bind("focus", function() {
		$(this).removeClass("empty");
		$(this).attr("value", "");
	});
	input.bind("blur", function() {
		if($(this).attr("value") == "") {
			$(this).addClass("empty");
			$(this).attr("value", text);
		}
	});
	button.bind("click", function() {
		if(input.attr("value") == text) {
			input.attr("value","");
		}
	});
}

function CreateBookmarkLink(el) {
	title = el.title;
	url = el.href;
	
	if (!window.sidebar && window.external) { // IE Favorite
		window.external.AddFavorite(url, title);
		return false;
	} else {
		return true;
	}
};

function SaveSearchAsBookmark() {
	var query = $("#searchForm input[name='keywords']").attr("value");
	if(query.length > 0)
		query = query + " - ";

	CreateBookmarkLink(query + document.title, location.href);
};

function InitDatePicker(el) {
	$(el).datepicker({
		showOn: "both", 
		buttonImage: "images/calendar.gif", 
		buttonImageOnly: true,
		dateFormat: "dd.mm.yy",
		closeText: 'Fertig', // Display text for close link
		prevText: 'Zur&uuml;ck', // Display text for previous month link
		nextText: 'Weiter', // Display text for next month link
		currentText: 'Heute', // Display text for current month link
		monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni', 'Juli','August','September','Oktober','November','Dezember'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'M&auml;r', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], // For formatting
		dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], // For formatting
		dayNamesShort: ['Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam'], // For formatting
		dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'], // Column headings for days starting at Sunday
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false // True if right-to-left language, false if left-to-right
	});	
};

$(document).ready(function() {
	$("input.autofocus").focus();
});

var ImageUpload = {
	addBlock: function(block, formId, previewBlock) {
		block = $(block);
		block.show();
		
		var method = {};
		if(previewBlock) {
			method.remove = "image/deletePreviewImage.do";
			method.upload = "image/uploadPreviewImage.do";
		} else {
			method.remove = "image/deleteImage.do";
			method.upload = "image/uploadImage.do";
		}
		
		var func = function(input) {	
			var randId = Math.floor(Math.random()*999999999);
			var iframe;
			
			try {
				// INTERNET EXPLORER FUCKING SUUUUUUUUUUCKS
				iframe = $(document.createElement('<iframe name="imageUploadFrame_'+randId+'">'));				
			} catch (ex) {
				iframe = $(document.createElement("iframe"));
			}
			iframe.attr("name", "imageUploadFrame_" + randId);
			iframe.attr("id", "imageUploadFrame_" + randId);
			iframe.attr("src", "about:blank");
			iframe.hide();
			$("body").append(iframe);
			
			var form = $(document.createElement("form"));
			form.hide();
			$("body").append(form);
			form.append($(document.createElement("input")).attr("type", "hidden").attr("name", "formId").attr("value", formId));
			var old = input;
			input = old.clone();
			input.attr("disabled", "disabled");
			input.bind("change", function() {
				func($(this));
			});
			old.after(input);
			old.attr("name", "image");
			form.append(old);
			form.attr("action", method.upload);
			form.attr("method", "POST");
			form.attr("enctype", "multipart/form-data");
			form.attr("encoding", "multipart/form-data");
			form.attr("target", "imageUploadFrame_" + randId);
			
			form.submit();
			
			iframe.bind("load", function() {
				var response = $("#imageUploadFrame_"+randId).contents().text();
				var json = null;
				eval("json = " + response + ";");
				if(json != null) {
					ImageUpload.createImageEl(block, input, method, formId, json);
					iframe.remove();
				}
			});
			
			form.remove();
		} 
		
		block.find(".inputs input").bind("change", function() {
			func($(this));
		});
		
		block.find(".previewImages .image input").each(function() {
			var input = block.find(".inputs input:not(:disabled):first");
			input.attr("disabled", "disabled");
			$(this).bind("click", function() {
				ImageUpload.deleteImage($(this), input, method, formId);
			});
		});
	},
	deleteImage: function(el, input, method, formId) {
		$.get(method.remove, {imageId:$(el).parent().attr("imageId"), formId:formId}, function() {
			input.attr("disabled", "");
			input.attr("value", "");
			$(el).parent().remove();
		});
	},
	createImageEl: function(block, input, method, formId, image) {
		var btn = $(document.createElement("input"));
		btn.attr("type", "button");
		btn.attr("value", "Löschen");
		btn.bind("click", function() {
			ImageUpload.deleteImage($(this), input, method, formId);
		});
		
		var div = $(document.createElement("div"));
		div.addClass("image");
		div.attr("imageId", image.id);
		var img = $(document.createElement("img"));
		img.attr("src", image.url);
		
		
		div.append(img);
		div.append("<br />");
		div.append(btn);
		
		block.find(".previewImages").append(div);
	}
};

var CategorySelect = {
	init: function(mainCatId) {
		$("#categorySelect").show();
		$("#categorySelect .mainCategories")
			.attr("disabled", null)
			.change(function() {
				CategorySelect.updateSubCats($(this).val());
			});
		this.updateSubCats(mainCatId);
	},
	updateSubCats: function(mainCatId) {
		$("#categorySelect .subCategories").each(function() {
			$(this).hide();
			if($(this).hasClass("catId_" + mainCatId)) {
				$(this).attr("disabled", null);
				$(this).show();
			}
		});
	}
}

var MyAdverts = {
	init: function() {
		$("table.adverts td.category").bind("mouseover", function() {
			MyAdverts.focus($(this), "category");
		});
		$("table.adverts td.category").bind("mouseout", function() {
			$(this).parent().siblings().css("opacity", "1");
		});
		$("table.adverts td.date").bind("mouseover", function() {
			MyAdverts.focus($(this), "date");
		});
		$("table.adverts td.date").bind("mouseout", function() {
			$(this).parent().siblings().css("opacity", "1");
		});
		$.tablesorter.addParser({ 
	        // set a unique id 
	        id: 'date', 
	        is: function(s) {
	            return false; 
	        }, 
	        format: function(string) { 
	        	//console.log("Date format: '"+s+"'");
				var result = string.match(/([0-9]+)\.([0-9]+)\.([0-9]+) <em>([0-9]+):([0-9]+)<\/em>/);
				return result[3] + result[2] + result[1] + result[4] + result[5]; 
	        },
	        type: 'numeric' 
	    });
		$.tablesorter.addParser({ 
	        // set a unique id 
	        id: 'price', 
	        is: function(s) {
	            return false; 
	        }, 
	        format: function(string) { 
	        	//console.log("Date format: '"+s+"'");
	        	if(string == "")
	        		return 0;
	        	else
	        		return parseFloat(string.replace(/\./g,"").replace(/,/g,"."));
	        },
	        type: 'numeric' 
	    });			
		var params = {
			cssAsc: "asc",
			cssDesc: "desc",
			sortList: [[0,1], [1,0]],
			headers: {
				0: {
					sorter:'date'
				},
				4: {
					sorter:'price'
				},
				6: {
					sorter:false
				}
			},
			widgets: ['zebra']
		};
		$("table.adverts").tablesorter(params);
		//$("table.adverts.unverified").tablesorterPager({container: $(".pager.unverified"), positionFixed: false, seperator: " von ", size: 10});
		//$("table.adverts.verified").tablesorterPager({container: $(".pager.verified"), positionFixed: false, seperator: " von ", size: 30});
		//$("table.adverts.deleted").tablesorterPager({container: $(".pager.deleted"), positionFixed: false, seperator: " von ", size: 10});
	},
	focus: function(td, cssClass) {
		$(td).parent().siblings().find("td." + cssClass).each(function() {
			if($(this).text() != $(td).text())
				$(this).parent().css("opacity", "0.4");
		});
	}
};