$(document).ready(bl_init);

function bl_init() {
	// if there is a input field checking the javascript state: set it on
	$('.js_check').val('on');
	
	// set focus
	$('.focusOnStart').focus();
	
	// activate image preview
	if ($('a.imgpreview').length > 0) {
		$('a.imgpreview').imgPreview();
	}
	if ($('a.imgpreviewrel').length > 0) {
		$('a.imgpreviewrel').imgPreview({srcAttr: 'rel', distanceFromCursor: {top: -40, left: 10 }});
	}
	
	// activate content description
	if ($('a.cluetip_content').length > 0) {
		$('a.cluetip_content').cluetip({'local': true, 'sticky': false, 'clickThrough': true, 'width': 350, 'positionBy': 'mouse'});
	}
	
	$('#agblink').click(function() {
		var uid = $('#agblink').attr("href").replace(/.*vendoruID=(\d+).*/, "$1")
		showAGB(uid);
		return false;
		}
	);
	
	// backgrounds for login
	var loginPass = $('#loginPass');
	if (loginPass.length > 0 && loginPass.val() == '') {
		loginPass.css('backgroundImage', "url(/images/login_passwort_bg.gif)");
	}
	var loginName = $('#loginName');
	if (loginName.length > 0 && loginName.val() == '') {
		loginName.css('backgroundImage', "url(/images/login_benutzername_bg.gif)");
	}
	
	// show hidden search fields
	$("#showFullSearch").click(showFullSearchFields);
	
	// activate special behaviour for game format
	$("#input_sparte1ID").change(toggleGameFormatInput);
	
	// back links
	$('.jsBack').show().click(function() {
		history.back();
		return false;
        }
	);
	
	// swap labels
	$('.quickSearchSwapLabel').click(function() {
		bl_quickSearchSwapLabel(jQuery(this).val());
        }
	);
	
	// confirm action in links
	$('.confirmAction').click(function() {
        var answer = confirm(jQuery(this).attr('title'));
        return answer;
        }
	);
	
	initAutocomplete();
	
	// Google Plus One
	var googleplusone = $('#googleplusone'); 
	if (googleplusone.length > 0) {
		googleplusone.html("<img id='gplusimg' src='/images/gplus_grey.png'/>");
		googleplusone.bind('click', function() {
			// modified code from http://www.heise.de/extras/socialshareprivacy/
			var uri = document.location.href;
			var canonical = $('link[rel="canonical"]').attr("href");
            if (canonical && canonical.length > 0) {
            	if (canonical.indexOf("http") < 0) {
            		canonical = document.location.protocol + "//" + document.location.host + canonical;
            	}
            	uri = canonical;
            }
            var gplus_code = '<div class="g-plusone" data-size="medium" data-count="false" data-href="' + uri + '"></div><script type="text/javascript">window.___gcfg = {lang: "de"}; (function(){ var po = document.createElement("script"); po.type = "text/javascript"; po.async = true; po.src = "https://apis.google.com/js/plusone.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s); })(); </script>';
			$('#gplusimg').replaceWith(gplus_code);
			googleplusone.trigger('hideCluetip');
			googleplusone.cluetip({});
			return false;
		})
	}
	
	// call init of page
	if (typeof page_init == 'function') {
		page_init();
	} 
}


function showAGB(vendoruID) {
	if (vendoruID == 0) {
		window.open('/pages/agb_booklooker.php?show=popup', '_blank', 'width=485,height=400,toolbar=0,location=0,directory=0,menubar=0,status=0,scrollbars=1,resizable=0');
	} else {
		window.open('/pages/agb.php?vendoruID=' + vendoruID, '_blank', 'width=500,height=400,toolbar=0,location=0,directory=0,menubar=0,status=0,scrollbars=1,resizable=0');
	}
}


function bl_quickSearchSwapLabel(mediaType) {
	mediaType = parseInt(mediaType);
	switch(mediaType) {
	case 0:
	case 3:
	case 4:
		$('#quickSearchLabel').html('Autor/in');
		break;
	case 1:
		$('#quickSearchLabel').html('Darsteller/Regie');
		break;
	case 2:
		$('#quickSearchLabel').html('K&uuml;nstler/in');
		break;
	}
	if (mediaType == 4) {
		$('#quickSearchAuthorField').hide();
		$(".autocomplete_artist").val("");
	} else {
		$('#quickSearchAuthorField').show();
	}
	$("#mediaType").val(mediaType);
}


function bl_checkLen(Target, Target2) {
	var maxlength = 300;

	var StrLen = Target.value.length;
	if (Target2 && $(Target2).is(':visible')) {
		StrLen += Target2.value.length;
	}
	document.getElementById("laengenanzeigestr").firstChild.data = StrLen;

	if (StrLen >= maxlength) {
		StrLen = maxlength;
		document.laengenanzeige.src = "/images/blue_space.gif";
	}
	else {
		document.laengenanzeige.src = "/images/red_space.gif";
	}
	document.laengenanzeige.width = StrLen / 3;
}


function toggleGameFormatInput() {
	var format = $("#input_sparte1ID").val();
	if (format == 105 || format == 106) {
		$("#row_gameFormatID").removeClass("tempHidden");
		$("#input_gameFormatID").addClass("required");
	} else {
		$("#row_gameFormatID").addClass("tempHidden");
		$("#input_gameFormatID").removeClass("required");
	}
}


function showFullSearchFields() {
	$(".initiallyHidden").not('#spamCatcher').show();
	var format = $("#input_sparte1ID").val();
	if (format == 105 || format == 106) {
		$("#row_gameFormatID").removeClass("tempHidden");
	}
	$(this).hide();
	$("#saveAsSearchtask").hide();
	$("#searchBestseller").hide();
	return false;
}


function initAutocomplete() {
	var autocomplete = $("#autocomplete").val();

	if (autocomplete != "on") return;

	$(".autocomplete_artist").autocomplete({  
		minLength: 2,
		position: { offset: "25 0" },
      source: function(req, add){
			var mediaType = $("#mediaType").val();
			var title = $(".autocomplete_title").length ? $(".autocomplete_title").val() : "";
			var publisher = $(".autocomplete_publisher").length ? $(".autocomplete_publisher").val() : "";
			$.getJSON("/ajx/suggest.php?mediaType=" + mediaType + "&field=artist&title=" + title + "&publisher=" + publisher + "&callback=?", req, function(data) {  
				var suggestions = [];
				$.each(data, function(i, val) {  
					suggestions.push(val);
             });  
				add(suggestions);  
			});  
		}  
	});  
	$(".autocomplete_title").autocomplete({  
		minLength: 2,
		position: { offset: "25 0" },
		source: function(req, add){  
			var mediaType = $("#mediaType").val();
			var artist = $(".autocomplete_artist").length ? $(".autocomplete_artist").val() : "";
			var publisher = $(".autocomplete_publisher").length ? $(".autocomplete_publisher").val() : "";
         $.getJSON("/ajx/suggest.php?mediaType=" + mediaType + "&field=title&artist=" + artist + "&publisher=" + publisher + "&callback=?", req, function(data) {  
             var suggestions = [];
             $.each(data, function(i, val) {  
            	 suggestions.push(val);
             });  
             add(suggestions);  
         });  
		}  
	});  
	$(".autocomplete_publisher").autocomplete({  
		minLength: 2,
		position: { offset: "25 0" },
		source: function(req, add){  
			var mediaType = $("#mediaType").val();
			var artist = $(".autocomplete_artist").length ? $(".autocomplete_artist").val() : "";
			var title = $(".autocomplete_title").length ? $(".autocomplete_title").val() : "";
			$.getJSON("/ajx/suggest.php?mediaType=" + mediaType + "&field=publisher&artist=" + artist + "&title=" + title + "&callback=?", req, function(data) {  
				var suggestions = [];
				$.each(data, function(i, val) {  
                suggestions.push(val);
				});  
				add(suggestions);  
			});  
		}  
	}); 
	$("#autocomplete_all").autocomplete({  
		minLength: 2,
		html: true,
		source: "/ajx/suggest_all.php",
		select: function( event, ui ) {
			if (ui.item) {
				var id = ui.item.id;
				var mediaType = id.substr(-1, 1);
				var field = id.substr(-3, 1);
				$("#guess_mediaType").val(mediaType);
				$("#guess_field").val(field);
				$("#autocompleted").val(ui.item.value);
				$("#autocomplete_all").val(ui.item.value);
				$("#schnellsuche").submit();
			} else {
				$("#guess_mediaType").val("");
				$("#guess_field").val("");
				$("#autocompleted").val("");
			}
		}
	});
	$('#schnellsuche').submit(function() {
		if ($.trim($("#autocomplete_all").val()) != $.trim($("#autocompleted").val())) {
			$("#guess_field").val("");
			$("#autocompleted").val("");
		}
		return true;
	});
}

