var galleryPopupTimeout;
var galleryClearTimeout;
var myDart;
var arrData                 = new Array();

jQuery(document).ready(function() {

    jQuery("img.galleryFeature").bind("mouseenter", function() {
            var tmp = jQuery(this).attr("class").match(/(^|\s)(\d+)(\s|$)/);
            if(tmp[2] != undefined) {
                    var anzid = tmp[2];
                    clearGalleryTimeouts();
                    galleryPopupTimeout = window.setTimeout("showGalleryPopup(" + anzid + ")", 1000);
            }
    }).bind("mouseleave", function(){
            clearGalleryTimeouts();
            galleryClearTimeout = window.setTimeout("hideGalleryPopup()", 500);
    });
    jQuery("div.galleryPopup").bind("mouseenter", function() {
    	clearGalleryTimeouts();
    	window.clearInterval(galleryClearTimeout);
    }).bind("mouseleave", function(){
    	clearGalleryTimeouts();
    	galleryClearTimeout = window.setTimeout("hideGalleryPopup()", 500);
    });
    jQuery(".closePopup").click(function() {
    	clearGalleryTimeouts();
    	hideGalleryPopup();
    });
});

function clearGalleryTimeouts() {
	try {
		window.clearInterval(galleryPopupTimeout);
	} catch(e) {}
	try {
		window.clearInterval(galleryClearTimeout);
	} catch(e) {}
}

function addMemo(anz_id) {
    jQuery('document').ready(function(){
        var strKleinanzeigenPath = jQuery.ajax({
            type    : 'GET',
            url     : '/ajax/crossdomain/kleinanzeigen/getInfo.php',
            data    : 'id=pathAzl',
            async   : false
        }).responseText;
        window.open(strKleinanzeigenPath+'memoinsert.php?tue=add&anz_id='+anz_id+'&coop=0','memoins','width=1,height=1,screenX=0,screenY=0,top=0,left=0');
    });
}

function popup(url, name, size_and_location, attributes) {
    var tokArray1 = size_and_location.split(";");
    var bef = "";

    if (typeof tokArray1[0] !="undefined") { bef = bef + "width=" + tokArray1[0]; }
    if (typeof tokArray1[1] !="undefined") { bef = bef + ",height=" + tokArray1[1]; }
    if (typeof tokArray1[2] !="undefined") { bef = bef + ",left=" + tokArray1[2]; }
    if (typeof tokArray1[3] !="undefined") { bef = bef + ",top=" + tokArray1[3]; }

    var tokArray2 = attributes.split(";");

    if (tokArray2[0]=="all") {
            bef = bef + ",location=yes";
            bef = bef + ",menubar=yes";
            bef = bef + ",resizable=yes";
            bef = bef + ",scrollbars=yes";
            bef = bef + ",status=yes";
            bef = bef + ",toolbar=yes";
    } else {
            for(i=0;i<tokArray2.length;i++) { bef = bef + "," + tokArray2[i] + "=yes"; }
    }

    w = eval(window.open(url, name, bef));
    w.focus();
}

function showGalleryPopup(anzid) {
	// Erstmal alles leeren
	jQuery("div.galleryPopup a.anzLink").attr("href", "javascript: void(0);");
	jQuery("div.galleryPopup p.anzText").html("");
	jQuery("div.galleryPopup img.imgThumb:visible").remove();
	jQuery("div.galleryPopup img.imgPreview").attr("src", "/images/blank.gif");
	jQuery("div.galleryPopup div.imgPreviewDiv").hide();

	var popupHeight = 550;
	var popupWidth = 550;
	var myPadding = 10;
	var dartWidth = 27;
	var dartHeight = 27;

	var pageHeight = $.jsBox.getPageHeight();

	var imagePosition = jQuery("img.galleryFeature." + anzid).position();
	var imageOffset = jQuery("img.galleryFeature." + anzid).offset();
	var xPos = imagePosition['left'];
	var yPos = imagePosition['top'];

	var spaceTop = imageOffset['top'] - jQuery(document).scrollTop() - myPadding;
	var spaceBottom = pageHeight - spaceTop - myPadding;
	var imageHeight = jQuery("img.galleryFeature." + anzid).height();

	if (spaceTop >= (popupHeight / 2) && spaceBottom >= (popupHeight / 2)) {
	    // mittig ausrichten, ist genug Platz da
	    positionTop = imagePosition['top'] - (popupHeight / 2) + (imageHeight / 2);
	}
	else if (spaceTop >= (popupHeight / 2)) {
	    // drüber ist genug Platz für zumindest das halbe Popup
	    positionTop = imagePosition['top'] - popupHeight + spaceBottom + imageHeight - (popupHeight / 5);
	}
	else {
	    // vielleicht ist drunter genug Platz, drüber jedenfalls nicht
	    positionTop = imagePosition['top'] - spaceTop;
	}
    var dartTop = Math.floor((imagePosition['top'] + (imageHeight / 2) - (dartHeight / 2)));

    if ((dartTop + dartHeight) > (positionTop + popupHeight)) {
    	// falls der Pfeil weiter unten ist als das Popup, dann verschieben wir das Popup um diese Differenz nach unten
    	positionTop += (dartTop - (positionTop + popupHeight)) + dartHeight;
    }
    else if (dartTop < positionTop) {
    	// falls der Pfeil weiter oben ist als das Popup, dann verschieben wir das Popup um diese Differenz nach oben
    	positionTop -= (positionTop - dartTop);
    }

	var pageWidth = getPageWidth();

	var imageWidth = jQuery("img.galleryFeature." + anzid).width();
	var spaceLeft = imageOffset['left'] - jQuery(document).scrollLeft() + myPadding;
	var spaceRight = pageWidth - spaceLeft - imageWidth - myPadding;

	if (spaceRight >= popupWidth) {
	    // rechts ist genug Platz
	    positionLeft = imagePosition['left'] + imageWidth + myPadding + dartWidth;
	    var dartLeft = imagePosition['left'] + imageWidth + myPadding;
	    myDart = jQuery("div#galleryPopupDartLeft");
	}
	else if (spaceLeft >= popupWidth) {
	    // rechts ist nicht genug Platz, dafür aber links
	    positionLeft = imagePosition['left'] - popupWidth - myPadding - dartWidth;
	    var dartLeft = imagePosition['left'] - myPadding;
	    myDart = jQuery("div#galleryPopupDartRight");
	}
	else {
	    // rechts und links kein Platz - also default und ab nach rechts
	    positionLeft = imagePosition['left'] + imageWidth + myPadding + dartWidth;
	    var dartLeft = imagePosition['left'] + imageWidth + myPadding;
	    myDart = jQuery("div#galleryPopupDartLeft");
	}

	jQuery("div.galleryPopup")
		.css("left", positionLeft + "px")
		.css("top", positionTop + "px");
	// den Pfeil anzeigen
	jQuery(myDart).css({left: dartLeft + "px", top: dartTop + "px"}).show();

	// Jetzt können wir es anzeigen
	jQuery("div.adVideo").css("visibility", "hidden");
	jQuery("div.galleryPopup").addClass('ajax_loading');
	jQuery("div.galleryPopup").show();

	// Füllen des Popups; entweder mit den Daten des Cache-Arrays, oder mit denen vom JSON
	if(arrData[anzid]) {
		fillPopup(arrData[anzid]);
	} else {
		var url = "/ajax/crossdomain/kleinanzeigen/azl_previewAd.php?id=" + anzid;
		jQuery.getJSON(url, function(data){
			arrData[anzid] = data;
			fillPopup(data);
	    });
	}
}

function hideGalleryPopup() {
	jQuery(myDart).hide();
	jQuery("div.galleryPopup").hide();
	jQuery("div.adVideo").css("visibility", "visible");
}

// Befüllen des Popups
function fillPopup(data) {
	var anzLink = data.url + "/" + SID1;
	jQuery("div.galleryPopup a.anzLink").attr("href", anzLink);
	jQuery("div.galleryPopup div.imgPreviewDiv a.anzLink").attr("href", anzLink);

	var anzMemoPad = "javascript: addMemo(" + data.id + ");";
	jQuery("div.galleryPopup a.anzMemoPad").attr("href", anzMemoPad);

	var anzText = data.text;
	anzText = anzText.replace(/\<B\>/g, "<b><a href='" + anzLink + "'>");
	anzText = anzText.replace(/\<\/B\>/g, "</b></a>");
	jQuery("div.galleryPopup p.anzText").html(anzText);

	jQuery("div.galleryPopup img.imgThumb:visible").remove();
	if(data.fotos) {
		if(data.fotos.length >= 1) {
		var imgPreview = data.fotos[0];
		jQuery("div.galleryPopup img.imgPreview").attr("src", imgPreview);
		jQuery("div.galleryPopup div.imgPreviewDiv").show();
		if(data.fotos.length > 1) {
			jQuery.each(data.fotos, function(k, v) {
				var myObj = jQuery("div.galleryPopup img.imgThumb:hidden:first").clone();
			  	myObj.attr('src', v).insertAfter(jQuery('div.galleryPopup img.imgThumb:last')).show();
		    });
			jQuery("div.galleryPopup div.imgThumbDiv").show();
			jQuery("div.galleryPopup img.imgThumb:visible").bind("mouseenter", function() {
				jQuery("div.galleryPopup img.imgPreview").attr("src", jQuery(this).attr("src"));
			});
		}
		}
	} else {
		var imgPreview = staticServer + "/images/azl/nopic_445x333.gif";
		jQuery("div.galleryPopup img.imgPreview").attr("src", imgPreview);
		jQuery("div.galleryPopup div.imgPreviewDiv").show();
	}
	jQuery("div.galleryPopup").removeClass('ajax_loading');
}

// adapter from getPageSize() by quirksmode.com
function getPageWidth() {
  var windowWidth;
  if (self.innerWidth) {	// all except Explorer
    windowWidth = self.innerWidth;
  } else if (document.documentElement && document.documentElement.clientWidth) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
  }
  return windowWidth;
}