// Image Preview

function showHide(elementId) {
  try {
    var el = $("#"+elementId);
    if (el.is(':hidden')) {
      el.show();
    } else {
      el.hide();
    }
  } catch (e) {}
}

function showSize(first, second, third) {

  $('.'+first).hide();
  $('.'+second).hide();
  $('.'+third).show();
  
  $(".b_"+first).removeClass("on");
  $(".b_"+second).removeClass("on");
  $(".b_"+third).removeClass("on");
  
  $(".b_"+first).addClass("off");
  $(".b_"+second).addClass("off");
  $(".b_"+third).addClass("on");
  
}


function showPrices(first, second) {
	
  $('.'+first).hide();
  $('.'+second).show();
  
  first = first.replace('r_', 'b_');
	second = second.replace('r_', 'b_');
	
  $("."+first).removeClass("on");
  $("."+second).removeClass("on");
  
  $("."+first).addClass("off");
  $("."+second).addClass("on");
  
}

function addToLightbox(objektId) {
  ajaxRequest('/service', 'GET', {ajax: "ImagePreviewAjax", action: "addToLightbox", objekt: objekt}, null, true);
}

function showSendPreview() {
	$('#sendToEmailBox').remove();
	$('body').append('<div id="sendToEmailBox" style="z-index:999999;"></div>');
	$('#sendToEmailBox').html($('#sendToEmail').html());
	$("#sendToEmailBox").dialog("destroy");
	$("#sendToEmailBox").dialog({ autoOpen: false, closeOnEscape: true, resizable: false, draggable: true, modal: true, width: 400, position: 'center', zIndex: 99999, title: sendPictureToMailMsg });
	$('#sendToEmailBox').dialog('open');
	return false;
}
	
function sendPreview() {
  var mail = $('#sendToEmailBox [name=ste_email]').val();
  var indexType = $('#indexType').val();
  if (mail == "") { return alert(emptyEmailMsg); }
  var regex = /^([a-z0-9_\-\.])+\@([a-z0-9_\-\.])+\.([a-z]{2,4})$/i;
  if (regex.test(mail) == false) { return alert(invalidEmailMsg); }
  $('#sendToEmailBox #sendToEmailForm').hide();
  $('#sendToEmailBox #sendToEmailLoader').show();
  ajaxRequest('/service', 'GET', {ajax: "ImagePreviewAjax", action: "sendPreview", objekt: objekt, mail: mail, 'indexType': indexType}, null, true, 'sendFinish');
}

function showSendTwitter(tweet) {
	var url = 'http://twitter.com/?status=' + tweet;
	window.open(url, "Twitter","status=1,toolbar=0,location=1,width=800,height=600"); 
	return false;
}

function report() {
  alert(reportAlertMsg);
  return false;
}

function selectAllKeywords() {
  $('[name="searchKeywords"]').each(function(i) {
    $(this).attr('checked', true);
  });
}

function selectNoneKeywords() {
  $('[name="searchKeywords"]').each(function(i) {
    $(this).attr('checked', false);
  });
}


/* New search from keywords - redirect */
function searchSelectedKeywords() {

  var keywords = new Array();
  $('[name="searchKeywords"]').each(function(i) {
    if ($(this).attr('checked') == true) {
      keywords[keywords.length] = $(this).val().replace(/ /, '').replace(/ /g, '+');
    }
  });
    
  if (keywords.length > 0) {
    location.href = '/' + stockType + '/' + keywords.join('+');
  }
  
}

function switchKeywords(lang) {
  if (lang == 'en') {
    var newId = 'english';
    var oldId = 'translate';
  } else {
    var newId = 'translate';
    var oldId = 'english';
  }

  newTitle    = $("#"+newId+'_title');
  newImgTitle = $("#"+newId+'_img_title');
  newDesc     = $("#"+newId+'_description');
  newKeywords = $("#"+newId+'_keywords');
  
  if (newTitle.html() == '') {
    newTitle.html((lang == 'en' ? pictureTitle : translatedPictureTitle));
  }
  if (newImgTitle.html() == '') {
    newImgTitle.html((lang == 'en' ? pictureTitle : translatedPictureTitle));
  }
  if (newDesc.html() == '') {
    newDesc.html((lang == 'en' ? pictureDescription : translatedPictureDescription));
  }
  if (newKeywords.html() == '') {
    ajaxRequest('/service', 'GET', {ajax: "ImagePreviewAjax", action: "getKeywords", lang: lang, id: objekt, editorial: editorialContent}, null, false, null, null, newKeywords.attr('id'));
  }
  
  newTitle.show();
  newImgTitle.show();
  newDesc.show();
  newKeywords.show();
  
//  $("#"+newId+'_tab').attr("class", "selecttab");
//  $("#"+newId+'_tab').attr("className", "selecttab");
  $("#"+oldId+'_title').hide();
  $("#"+oldId+'_img_title').hide();
  $("#"+oldId+'_description').hide();
  $("#"+oldId+'_keywords').hide();
//  $("#"+oldId+'_tab').attr("class", "");
//  $("#"+oldId+'_tab').attr("className", "");
  
  if (lang == "en") {
	  $(".switch-translate-original").hide();
	  $(".switch-translate-translation").show();
  } else {
	  $(".switch-translate-translation").hide();
	  $(".switch-translate-original").show();
  }
  
  
  // Record selection
  ajaxRequest('/service', 'GET', {ajax: "ImagePreviewAjax", action: "saveLangSelection", lang: lang}, false, true);
}

function exif(on) {
  if (on == 1) {
    $("#shortExif").hide();
    $("#longExif").show();
  } else {
    $("#shortExif").show();
    $("#longExif").hide();
  }
}

String.prototype.pad = function(l, s, t) {
  return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
      + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
      + this + s.substr(0, l - t) : this;
};

function downloadFreeImageByMail() {
	try { _gaq.push(['_trackEvent', 'Image detail', 'Free image', 'Download by email']); } catch (e) {}
	try {
	
		var email 	= $('#downloadFreeImageBox #getFreeImage_email').val();
		var sizeId 	= $('[name=free_sizeId]').val();
		var priceId = $('[name=free_priceId]').val();
		var hash 		= $('[name=free_hash]').val();
		var objectId = $('[name=free_objectId]').val();
		$('#downloadFreeImageBox #getFreeImage_email').val(sendingMsg);
		
		$.post("/service", { ajax: "ImagePreviewAjax", action: "downloadFreeImage",
			email: email, sizeId: sizeId, priceId: priceId, hash: hash, objectId: objectId
		}, function(data) {
			$('#downloadFreeImageBox #getFreeImage_form').fadeOut();
			if (data == 'OK') {
				setTimeout("$('#downloadFreeImageBox #getFreeImage_msg_success').fadeIn();", 500);
			} else {
				setTimeout("$('#downloadFreeImageBox #getFreeImage_msg_error').fadeIn();", 500);
			}
		});
	} catch (e) {
		alert(e);
	}
}


/* Extended licenses */
var clickExtendedLicenseInfo = false;
var lastExtendedLicenseInfo = '';
var elMouseLeft = 0;
var elMouseTop = 0;

function extendedLicenseInfo(name, key) {

	$('#extendedLicenseInfo').hide();

	if (lastExtendedLicenseInfo == name) {
		lastExtendedLicenseInfo = '';
		return false;
	}
	
	clickExtendedLicenseInfo = true;
	if (key) {
		var pos = $('.extended_info_' + key).position();
	} else {
		var pos = $('#el_info_pos_' + name).position();
	}
	$('#extendedLicenseInfo').css('top', (elMouseTop + 5) + 'px');
	$('#extendedLicenseInfo').css('left', (elMouseLeft + 5) + 'px');
	try {
		$('#extendedLicenseInfo').html(elDescriptions[name]); // + "\n" + "<a href=\"" + completeElInfoUrl + "#" + name + "\">" + completeElInfo + " &raquo;</a>");
	} catch (e) {
		$('#extendedLicenseInfo').text(errorElDescription);
	}
	
	$('#extendedLicenseInfo').fadeIn('fast');
	lastExtendedLicenseInfo = name;
	setTimeout("clickExtendedLicenseInfo = false;", 200);
	return false;
}

$('body').click(function() {
	if (clickExtendedLicenseInfo == false) {
		$('#extendedLicenseInfo').fadeOut('fast');
	}
});

jQuery(document).ready(function() {
   $(document).mousemove(function(e){
   	elMouseLeft = e.pageX;
   	elMouseTop = e.pageY;
   }); 
})



/* Similar and related */

function clickRelatedImages(type) {
	if (type == 'next' || type == 'previous') {
		$('#related_images .prevnext').hide();
		$('#related_images .ip_similar').hide();
		$('#related_images_loader').fadeIn(200);
		if (type == 'next') {
			++related_images_page;
		} else if (type == 'previous') {
			--related_images_page;
		}
		getRelatedImages();
	}
}


function moveRelatedImages(type) {
	var maxLeft = -($('#related_images .ip_similar a').length * 95);
	if (type == 'next') {
		if (parseInt($('#related_images .ip_similar').css('left')) < -437 && $('#relatedKeyboardMsg').length > 0) {
			$('#relatedKeyboardMsg').slideDown();
		}
		if ((parseInt($('#related_images .ip_similar').css('left')) - 437) > maxLeft) {
			$('#related_images .ip_similar').animate({ left: '-=437' });
		}
	} else if (type == 'previous') {
		if (parseInt($('#related_images .ip_similar').css('left')) < 0) {
			$('#related_images .ip_similar').animate({ left: '+=437' });
		}
	}
}

function getRelatedImages() {
	if (related_images_page > 1) {
		$('#related_images .prevnext .previous').show();
	} else {
		$('#related_images .prevnext .previous').hide();
	}
	$('#related_images').fadeIn();
	$.get("/service", { ajax: "SearchAjax", action: "getRelatedImages", objectId: objekt, page: related_images_page, index: stockType},
	function(data) {
		$('#related_images_loader').fadeOut(500);
		$('#related_images .ip_similar').hide();
		$('#related_images .ip_similar').html(data);
		setTimeout("$('#related_images .ip_similar').fadeIn(1000);", 800);
		setTimeout("$('#related_images .prevnext').fadeIn(1000);", 800);
	});
}

function moveSimilarImages(type) {
	var maxLeft = -($('#similar_images .ip_similar a').length * 95);
	if (type == 'next') {
		if (parseInt($('#similar_images .ip_similar').css('left')) < -380 && $('#similarKeyboardMsg').length > 0) {
			$('#similarKeyboardMsg').slideDown();
		}
		if ((parseInt($('#similar_images .ip_similar').css('left')) - 380) > maxLeft) {
			$('#similar_images .ip_similar').animate({ left: '-=380' });
		}
	} else if (type == 'previous') {
		if (parseInt($('#similar_images .ip_similar').css('left')) < 0) {
			$('#similar_images .ip_similar').animate({ left: '+=380' });
		}
	}
}

function clickSimilarImages(type) {
	if (type == 'next' || type == 'previous') {
		$('#similar_images .prevnext').hide();
		$('#similar_images .ip_similar').hide();
		$('#similar_images_loader').fadeIn(200);
		if (type == 'next') {
			++similar_images_page;
		} else if (type == 'previous') {
			--similar_images_page;
		}
		getSimilarImages();
	}
}

function getSimilarImages() {
	if (similar_images_page > 1) {
		$('#similar_images .prevnext .previous').show();
	} else {
		$('#similar_images .prevnext .previous').hide();
	}
	$('#similar_images').fadeIn();
	$.get("/service", { ajax: "SearchAjax", action: "getSimilarImages", objectId: objekt, page: similar_images_page},
	function(data) {
		$('#similar_images_loader').fadeOut(500);
		$('#similar_images .ip_similar').hide();
		$('#similar_images .ip_similar').html(data);
		setTimeout("$('#similar_images .ip_similar').fadeIn(1000);", 800);
		setTimeout("$('#similar_images .prevnext').fadeIn(1000);", 800);
	});
}

$('#submit_keyword').live('click', function() {
	try {
		_gaq.push(['_trackEvent', 'Search', 'Click', 'Keyword (detail)']);
	} catch (e) {}
});

$('#english_keywords h2 a').live('click', function() {
	try {
		_gaq.push(['_trackEvent', 'Search', 'Click', 'Keyword (detail)']);
	} catch (e) {}
});

$('#translate_keywords h2 a').live('click', function() {
	try {
		_gaq.push(['_trackEvent', 'Search', 'Click', 'Keyword (detail)']);
	} catch (e) {}
});

/**
 *	Show dialog box for downloading FREE image
 */ 
function downloadFreeImage(objectId, sizeId, priceId, hash) {
	$('#downloadFreeImageBox').remove();
	$('body').append('<div id="downloadFreeImageBox" style="z-index:999999;"></div>');
	$('#downloadFreeImageBox').html($('#downloadFreeImage').html());
	
	$("#downloadFreeImageBox").dialog("destroy");
	$("#downloadFreeImageBox").dialog({ autoOpen: false, closeOnEscape: true, resizable: false, draggable: true, modal: true, width: 400, position: 'center', zIndex: 99999, title: downloadFreeImageMsg });
	$('#downloadFreeImageBox').dialog('open');
	
	$('[name=free_objectId]').val(objectId);
	$('[name=free_sizeId]').val(sizeId);
	$('[name=free_priceId]').val(priceId);
	$('[name=free_hash]').val(hash);
	
	return false;
}

/**
 *	Show dialog box for downloading EDITORIAL image
 */ 
function downloadEditorialImage(objectId, sizeId, priceId, hash, toDownload, price) {
	
	$('#editorialRestrictionsBox').remove();
	$('body').append('<div id="editorialRestrictionsBox" style="z-index:999999;"></div>');
	$('#editorialRestrictionsBox').html($('#editorialRestrictions').html());
	
	$("#editorialRestrictionsBox").dialog("destroy");
	$("#editorialRestrictionsBox").dialog({ autoOpen: false, closeOnEscape: true, resizable: false, draggable: true, modal: true, width: 400, position: 'center', zIndex: 99999999, title: downloadEditorialMsg });
	$('#editorialRestrictionsBox').dialog('open');
	
	$('[name=e_objectId]').val(objectId);
	$('[name=e_sizeId]').val(sizeId);
	$('[name=e_priceId]').val(priceId);
	$('[name=e_hash]').val(hash);
	$('[name=e_price]').val(price);
	
	if (toDownload == 1) {
		$('#editorialRestrictionsBox .toDownload_0').hide();
		$('#editorialRestrictionsBox .toDownload_1').show();
	} else {
		$('#editorialRestrictionsBox .toDownload_1').hide();
		$('#editorialRestrictionsBox .toDownload_0').show();
	}
	
	return false;
}

/* ZOOM */

function PixmacZoom(id, type, zoomWidth, zoomHeight, previewWidth, previewHeight, tileSize) {
	this.id = id;
	this.type = type;
	this.zoomWidth = zoomWidth;
	this.zoomHeight = zoomHeight;
	this.previewWidth = previewWidth;
	this.previewHeight = previewHeight;
	this.tileSize = tileSize;

	this.setElements = function(zoomDiv, image, zoomIn, zoomOut, zoomWrap) {
		this.zoomDivId = zoomDiv;
		this.zoomImageId = image;
		this.zoomInId = zoomIn;
		this.zoomOutId = zoomOut;
		this.zoomWrapId = zoomWrap;
	}

	this.assignEvents = function() {
		var thisPixmacZoom = this;
		$('#' + this.zoomDivId).bind('click.zoom', function(event) {
			thisPixmacZoom.zoomImage(event);
			$('#' + thisPixmacZoom.zoomDivId).unbind('click.zoom'); 
		});
		$('#' + this.zoomDivId).mouseover(function() {
			thisPixmacZoom.showZoomInIco();
		});
		$('#' + this.zoomDivId).mouseout(function() {
			thisPixmacZoom.hideZoomInIco();
		});
		$('#' + this.zoomOutId).click(function() {
			thisPixmacZoom.cancelZoom();
			$('#' + thisPixmacZoom.zoomDivId).bind('click.zoom', function(event) {
				thisPixmacZoom.zoomImage(event);
				$('#' + thisPixmacZoom.zoomDivId).unbind('click.zoom'); 
			});
			return false;
		});
		$('#' + this.zoomDivId).mousedown(function(event) {
			if (!zoomed) {
				return false;
			}
			thisPixmacZoom.hideZoomInIco();
			event.preventDefault();
			largeZoomOffsets = [$('#' + thisPixmacZoom.zoomWrapId).offset().left, $('#' + thisPixmacZoom.zoomWrapId).offset().top];
			lastMouseX = event.pageX - largeZoomOffsets[0];
			lastMouseY = event.pageY - largeZoomOffsets[1];
			$(document).bind('mousemove.dragstart', function(event) {
				event.preventDefault();
				thisPixmacZoom.dragImage(event);
			});
			return false;
		});
		$(document).bind('mouseup', function(e) {
			showTrails = true;
			$(document).unbind('mousemove.dragstart');
		});
	}

	this.showZoomInIco = function () {
		if (!zoomed) {
			$('#' + this.zoomInId).show();
		}
	}
	
	this.hideZoomInIco = function () {
		$('#' + this.zoomInId).hide();
	}
	
	this.showZoomOutIco = function () {
		$('#' + this.zoomOutId).show();
	}
	
	this.hideZoomOutIco = function () {
		$('#' + this.zoomOutId).hide();
	}
	
	this.zoomImage = function (event) {
		var thisPixmacZoom = this;
		event.preventDefault();
		jQuery.get("/service", {"ajax": "ImageAjax", "action": "tileImage", "objectId": this.id}, function(data) {
			if (data == "success") {
				thisPixmacZoom.loadTiles();
			} else {
				$('#zoomTiles').html("");
				thisPixmacZoom.cancelZoom(id);
			}
		});
		var largeZoomOffsets = [$('#' + this.zoomWrapId).offset().left, $('#' + this.zoomWrapId).offset().top];
		var x = event.pageX - largeZoomOffsets[0];
		var y = event.pageY - largeZoomOffsets[1];
		lastMouseX = x;
		lastMouseY = y;
		var widthRatio = x / previewWidth;
		var heightRatio = y / previewHeight;
		var moveLeft = zoomWidth * widthRatio - (previewWidth / 2);
		var moveTop = zoomHeight * heightRatio - (previewHeight / 2);
		if (moveLeft < 0) { moveLeft = 0; }
		if (moveTop < 0) { moveTop = 0; }
		if (moveLeft > zoomWidth - 400) { moveLeft = zoomWidth - 400; }
		if (moveTop > zoomHeight - 400) { moveTop = zoomHeight - 400; }
		
		$('#' + this.zoomImageId).css("position", "absolute");
		$('#previewImageFakeDiv').css("height", "435px");
		$('#' + this.zoomWrapId).css("height", "400px");
		$('#' + this.zoomWrapId).css("border", "1px solid #666666");
		$('#' + this.zoomImageId).css("height", "400px");
		$('#' + this.zoomDivId).css("width", "400px");
		$('#' + this.zoomDivId).css("height", "400px");
		$('#' + this.zoomDivId).css("overflow", "hidden");
		
		$('#' + this.zoomWrapId).css("width", "400px");
		$('#' + this.zoomWrapId).css("left", "-425px");
									
		$('#' + this.zoomImageId).animate({
			width: thisPixmacZoom.zoomWidth + "px",
			height: thisPixmacZoom.zoomHeight + "px",
			left: (- moveLeft) + "px",
			top: (- moveTop) + "px"
		}, 400, function () {
			zoomed = true;
			$('#zoomPane').css("width", thisPixmacZoom.zoomWidth);
			$('#zoomPane').css("height", thisPixmacZoom.zoomHeight);
			$('#zoomPane').css("top", - moveTop);
			$('#zoomPane').css("left", - moveLeft);
			$('#zoomPane').css("position", "absolute");
			$('#zoomPane').css("overflow", "hidden");
			$('#' + thisPixmacZoom.zoomImageId).css("top", 0);
			$('#' + thisPixmacZoom.zoomImageId).css("left", 0);
			if (!$('#zoomTiles').html()) {
				thisPixmacZoom.createTileSkeleton();
			}
			$('#' + thisPixmacZoom.zoomDivId).css("cursor", "Move");
			$('#zoomTiles').show();
			thisPixmacZoom.hideZoomInIco();
			thisPixmacZoom.showZoomOutIco()
			thisPixmacZoom.loadTiles();
		});
	}
	
	this.createTileSkeleton = function() {
		var tableContent = "";
		for (i = 0; i < Math.floor(this.zoomHeight / this.tileSize) + 1; i++) {
			for (j = 0; j < Math.floor(this.zoomWidth / this.tileSize) + 1; j++) {
				if (j == Math.floor(this.zoomWidth / this.tileSize) && i == Math.floor(this.zoomHeight / this.tileSize)) {
					var width = this.zoomWidth % this.tileSize;
					var height = this.zoomHeight % this.tileSize;
					tableContent += '<div id="tile-' + i + '-' + j+ '" style="width: ' + width + 'px; height: ' + height + 'px;"></div>';
				} else if (j == Math.floor(this.zoomWidth / this.tileSize)) {
					var width = this.zoomWidth % this.tileSize;
					tableContent += '<div id="tile-' + i + '-' + j+ '" style="width: ' + width + 'px;"></div>';
				} else if (i == Math.floor(this.zoomHeight / this.tileSize)) {
					var height = this.zoomHeight % this.tileSize;
					tableContent += '<div id="tile-' + i + '-' + j+ '" style="height: ' + height + 'px;"></div>';
				} else {
					tableContent += '<div id="tile-' + i + '-' + j+ '"></div>';
				}
			}
			tableContent += "<br />";
		}
		$('#zoomTiles').html(tableContent);
	}
	
	this.loadTiles = function() {
		var leftTile = Math.abs(parseInt($('#zoomPane').css("left")));
		var topTile = Math.abs(parseInt($('#zoomPane').css("top")));
		leftTile = Math.floor(leftTile / this.tileSize);
		topTile = Math.floor(topTile / this.tileSize);
		
		this.loadTile(leftTile, topTile); 	 	this.loadTile(leftTile + 1, topTile); 	  this.loadTile(leftTile + 2, topTile);
		this.loadTile(leftTile, topTile + 1); 	this.loadTile(leftTile + 1, topTile + 1); this.loadTile(leftTile + 2, topTile + 1);
		this.loadTile(leftTile, topTile + 2); 	this.loadTile(leftTile + 1, topTile + 2); this.loadTile(leftTile + 2, topTile + 2);
	}
	
	this.loadTile = function(leftTile, topTile) {
		var tileSrc = "http://tiles.pixmac.com/" + leftTile.toString().pad(2,"0",0) + "-" + topTile.toString().pad(2,"0",0) + "-" + this.id + ".jpg?r=" + Math.floor(Math.random() * 5000);
		var onError = "pixmacZoom.loadTileError(" + leftTile + ", " + topTile + ")";
		if (!$('#tile-' + topTile + '-' + leftTile).html() || $('#tile-' + topTile + '-' + leftTile + ' img').attr("errorCode") == "1") {
			this.displayLoading(1000);
			$('#tile-' + topTile + '-' + leftTile).html('<img src="' + tileSrc + '" onError="' + onError + '" />');
			$('#tile-' + topTile + '-' + leftTile + ' img').attr("errorCode", "0");
		}
	}
	
	this.loadTileError = function(leftTile, topTile) {
		if (this.type == 1 || this.type == 3) {
			var time = 1000 + Math.floor(Math.random()*2000);
			this.displayLoading(time);
			$('#tile-' + topTile + '-' + leftTile + ' img').attr("errorCode", 1);
			setTimeout("pixmacZoom.loadTile(" + leftTile + ", " + topTile + ")", time);
		} else if (imageType == 2) {
			// TODO display loading do doby, nez se to nacte?
//			var image = new Image();
//			image.src = "http://zoom.fotolia.com/Content/Zoom/5.40749999966714/201.60785880511472/133.2447550242029/?path=http%3A//static-p4.fotolia.com/jpg/00/09/75/83/400_F_9758333_DbqKvGaUFKO6N74amOrevTIxfk1W6XE9.jpg";
//			var canvas = document.createElement("canvas");
//			var context = canvas.getContext("2d");
//			image.onload = function() {
//				alert(canvas);
//				alert("image loaded");
//				context.drawImage(image, 0, 0);
//				var pixels = context.getImageData(0, 0, 1, 1).data;
//				alert(pixels[0] + " " + pixels[1] + " " + pixels[2]);
////				context.beginPath();
////				context.moveTo(30,96);
////				context.lineTo(70,66);
////				context.lineTo(103,76);
//				alert("image drawn");
//				alert(canvas.toDataURL());
//			}
//			this.displayLoading(5000);
//			var tileSrc = "http://" + location.hostname + "/fotolia-zoom/id/" + this.id + "/left/" + leftTile + "/top/" + topTile;
//			$('#tile-' + topTile + '-' + leftTile).html('<img src="' + tileSrc + '" />');
		}
	}
	
	this.displayLoading = function(displayTime) {
		if (!displayTime) {
			displayTime = 1000;
		}
		$('#loadingTiles').show();
		setTimeout("$('#loadingTiles').hide()", displayTime);
	}
	
	this.cancelZoom = function() {
		var thisPixmacZoom = this;
		$('#' + this.zoomImageId).animate({
			width: this.previewWidth + "px",
			height: this.previewHeight + "px",
			left: 0 + "px",
			top: 0 + "px"
		}, 500, function() {
			thisPixmacZoom.showZoomInIco();
			thisPixmacZoom.hideZoomOutIco();
			zoomed = false;
			$('#zoomPane').css("width", previewWidth);
			$('#zoomPane').css("height", previewHeight);
			$('#zoomPane').css("position", "static");
			$('#zoomTiles').hide();
			$('#' + thisPixmacZoom.zoomWrapId).css("left", imageDetailPositionLeft);
			$('#' + thisPixmacZoom.zoomWrapId).css("width", imageDetailPositionWidth);
			$('#' + thisPixmacZoom.zoomDivId).css("cursor", "default");
			$('#' + thisPixmacZoom.zoomImageId).css("position", "absolute");
			$('#previewImageFakeDiv').css("height", (thisPixmacZoom.previewHeight + 35) + "px");
			$('#' + thisPixmacZoom.zoomWrapId).css("height", thisPixmacZoom.previewHeight + "px");
			$('#' + thisPixmacZoom.zoomWrapId).css("width", thisPixmacZoom.previewWidth + "px");
			$('#' + thisPixmacZoom.zoomWrapId).css("border", "0");
			$('#' + thisPixmacZoom.zoomImageId).css("height", thisPixmacZoom.previewHeight + "px");
			$('#' + thisPixmacZoom.zoomDivId).css("width", thisPixmacZoom.previewWidth + "px");
			$('#' + thisPixmacZoom.zoomDivId).css("height", thisPixmacZoom.previewHeight + "px");
		});
	}
	
	this.dragImage = function(event) {
		showTrails = false;
		var largeZoomOffsets = [$('#' + this.zoomWrapId).offset().left, $('#' + this.zoomWrapId).offset().top];
		var x = event.pageX - largeZoomOffsets[0];
		var y = event.pageY - largeZoomOffsets[1];
		var currentTop = parseInt($('#zoomPane').css('top'));
		var currentLeft = parseInt($('#zoomPane').css('left'));
		var newTop = currentTop + (y - lastMouseY);
		var newLeft = currentLeft + (x - lastMouseX);
		if (newTop > 0) { newTop = 0; }
		if (newLeft > 0) { newLeft = 0; }
		if (newTop < - (this.zoomHeight - 400)) { newTop = - (this.zoomHeight - 400); }
		if (newLeft < - (this.zoomWidth - 400)) { newLeft = - (this.zoomWidth - 400); }
//		document.title = "moving " + x + ", " + y;
//		document.title = "mf " + currentTop + "," + currentLeft + "to" + newTop + "," + newLeft;
		lastMouseX = x;
		lastMouseY = y;
		$('#zoomPane').css("left", newLeft);
		$('#zoomPane').css("top", newTop);
		this.loadTiles();
		return false;
	}

}



/**
 *
 *	New functions for price table on image detail
 *	 
 */

// Function for updating data for "download"					
function updateBuyForm(input) {
	var data = input.val().split('_');
	if (data.length > 1) {
		var sizeId 		= data[0];
		var priceId 	= data[1];
		var hash 			= data[2];
		var purchased = data[3];
		var downloadable = ((hash != '' && hash != 'NONE') ? true : false);
		
		$('#buyFormLink').attr('href', '/download/objectID/'+objekt+'/sizeID/'+sizeId+'/priceID/'+priceId+'/hash/'+hash);
		$('#buyFormSizeID').val(sizeId);
		$('#buyFormPriceID').val(priceId);
		$('#buyFormHash').val(hash);
		$('#buyFormPurchased').val(purchased);
		
	} else {
		var purchased = 'NO';
	}
	
	var price 		= $('#pricelistTotal').text();
	var credits 	= $('#creditsTotal').text();
	
	//downloadable == true && isAuthed == true && imageKindBalance > 0 && 
	if ((imageKindBalance >= parseFloat(credits)) || (purchased == 'YES')) {
		$('#rowTotalCredits').show();
		$('#rowTotalPrice').hide();
		if ($.browser.msie && (parseFloat(credits) > 0 || purchased == 'YES')) {
			$('#buyFormLink').show();
			$('#buyFormSubmit').hide();
		}
	} else {
		$('#rowTotalCredits').hide();
		$('#rowTotalPrice').show();
		if ($.browser.msie && (parseFloat(credits) > 0 || purchased == 'YES')) {
			$('#buyFormLink').hide();
			$('#buyFormSubmit').show();
		}
	}
		
	$('#buyFormPrice').val(price);
	$('#buyFormCredits').val(credits);
		
}
				
// Select large or fullsize on first document load 
function preSelectSize() {
	$('.priceRow').removeClass('active');
	$($('.priceRow').get().reverse()).each(function(i) {
		var input = $(this).find('input');
		if (input.attr('disabled') == true) {
			$('.moreCreditsNote').show();
		} else {
			var value = input.val().split('_');
			if (alreadyPreSelected == false && value[3] == 'YES') {
				input.attr('checked', true);
				$(this).addClass('active');
				alreadyPreSelected = true;
				recountTotalPrice();
				updateBuyForm(input);
			}
		}
	});
	
	if (alreadyPreSelected == false) {
		
		if (fullsizeId && fullsizeId != '' && $('#' + fullsizeId).length > 0) {
			
			var priceRow = $('#' + fullsizeId).parent().parent();
			var input = priceRow.find('input');
			if (alreadyPreSelected == false) {
				input.attr('checked', true);
				priceRow.addClass('active');
				alreadyPreSelected = true;
				recountTotalPrice();
				updateBuyForm(input);
			}
			
		} else {
			$('.priceRow').each(function(i) {
				var input = $(this).find('input');
				if (alreadyPreSelected == false && i > 1) {
					input.attr('checked', true);
					$(this).addClass('active');
					alreadyPreSelected = true;
					recountTotalPrice();
					updateBuyForm(input);
				}
			});
		}
		
	}
	
}

// If exists disabled input, show information message about it
function checkDisabledInputs() {
	$('.moreCreditsNote').hide();
	$('.priceRow').each(function() {
		if ($(this).hasClass('disabled') == true) {
			$('.moreCreditsNote').show();
		}
	});
/*
$('#extendedUsageBox').each(function() {
		if ($(this).hasClass('disabled') == true) {
			$('.moreCreditsNote').show();
		}
	});
*/
}


// Recount total price
function recountTotalPrice() {

	var price = 0;
	var credits = 0;
	
	$('.priceRow').each(function() {
		if ($(this).find('input').attr('checked') == true) {
			var rawPrice = $(this).find('.priceValue').text();
			if (!isNaN(rawPrice) && rawPrice != '') {
				price += parseFloat($(this).find('.priceValue').text());
			}
			var rawCredits = $(this).find('.credits').text();
			if (!isNaN(rawCredits) && rawCredits != '') {
				credits += parseFloat($(this).find('.credits').text());
			}
		}
	});
	
	$('.extendedLicenseRow').each(function() {
		if ($(this).find('input').attr('checked') == true) {
			var rawPrice = $(this).find('.priceValue').text();
			if (!isNaN(rawPrice) && rawPrice != '') {
				price += parseFloat($(this).find('.priceValue').text());
			}
			var rawCredits = $(this).find('.credits').text();
			if (!isNaN(rawCredits) && rawCredits != '') {
				credits += parseFloat($(this).find('.credits').text());
			}
		}
	});
	
	$('.extendedPriceRow').each(function() {
		if ($(this).find('input').attr('checked') == true) {
			var rawPrice = $(this).find('.priceValue').text();
			if (!isNaN(rawPrice) && rawPrice != '') {
				price += parseFloat(rawPrice);
			}
			var rawCredits = $(this).find('.credits').text();
			if (!isNaN(rawCredits) && rawCredits != '') {
				credits += parseFloat(rawCredits);
			}
		}
	});
	
	if ($('#pricelistTotal').length > 0) {
		price = number_format(price, currencyPrecision, '.', ' ');
		$('#pricelistTotal').text(price);
	}
	
	if ($('#creditsTotal').length > 0) {
		credits = number_format(credits, 0, '.', ' ');
		$('#creditsTotal').text(credits);
	}
	
}


function buy_photo_modal(objectId, sizeId, priceId, hash, price, promocode, guarantee) {
	$('#modal-buyphoto').dialog('open');
	$('#modal-buyphoto').load('/service', { ajax: "PopupAjax", action: "loadBuyPhoto", objectId: objectId, sizeId: sizeId, priceId: priceId, hash: hash, price: price, promocode: promocode, guarantee: guarantee});     
	return false; 
}

function p_buy_photo_modal(objectId, sizeId, priceId, hash, price) {
	$('#modal-buyphoto').dialog('open');
	$('#modal-buyphoto').load('/service', { ajax: "PopupAjax", action: "loadProfimediaBuyPhoto", objectId: objectId, sizeId: sizeId, priceId: priceId, hash: hash, price: price, profimediaEditorial: 1 });     
	return false; 
}
		
function buy_credits_modal(idCo) {
	$('#modal-buycredits').dialog('open');
	$('#modal-buycredits').load('/service', { ajax: "PopupAjax", action: "loadBuyCredits", idCo: idCo });     
	return false; 
}


$(function() {
	
	// Click on price row
	$('.priceRow').click(function() {
		var input = $(this).find('input');
		if (input.attr('disabled') != true) {
			$('.priceRow').removeClass('active');
			$('.extendedLicenseRow').removeClass('active');
			$('.priceRow').each(function() {
				$(this).find('input').attr('checked', false);
			});
			$('.extendedLicenseRow').each(function() {
				$(this).find('input').attr('checked', false);
			});
			input.attr('checked', true);
			$(this).addClass('active');
			recountTotalPrice();
			updateBuyForm(input);
			updateBuyCreditsPercent();
		}
		recountTotalPrice();
	});


	// Tabs price table
	$('#tabLicenseStandard').click(function() {
		$(this).parent().addClass('active');
		$('#tabLicenseExtended').parent().removeClass('active');
		$('#tableLicenseStandard').show();
		$('#tableLicenseStandardB').show();
		$('#tableLicenseExtended').hide();
		$('#tableLicenseExtendedB').hide();
	});
	$('#tabLicenseExtended').click(function() {
		$(this).parent().addClass('active');
		$('#tabLicenseStandard').parent().removeClass('active');
		$('#tableLicenseStandard').hide();
		$('#tableLicenseStandardB').hide();
		$('#tableLicenseExtended').show();
		$('#tableLicenseExtendedB').show();
	});
	$('#tableLicenseExtended').hide();
	
	// Show/hide extended options
/*
$('#extendedOptions').click(function() {
		if ($('#extendedUsageBox').is(':hidden')) {
			$('#extendedUsageBox').slideDown(200);
			$('#extendedOptions span').text('▲');
			$('#standardLicenseInfo').hide();
		} else {
			$('#extendedUsageBox').slideUp(200);
			$('#extendedOptions span').text('▼');
			//$('#standardLicenseInfo').show();
		}
	});
*/
	
	// Help popup
	$('#helpSize').click(function() {
		$('#modal-help').dialog('open');
		$('#modal-help').load('/service', { ajax: "PopupAjax", action: "loadHelp", helpType: "size"});     
	});
	$('#helpLicence').click(function() {
		$('#modal-help').dialog('open');
		$('#modal-help').load('/service', { ajax: "PopupAjax", action: "loadHelp", helpType: "licence"});
	});
	$('#helpLicencePersonal').click(function() {
		$('#modal-help').dialog('open');
		$('#modal-help').load('/service', { ajax: "PopupAjax", action: "loadHelp", helpType: "licencepersonal"});
	});

	// Active row on mouseover
	$('.priceRow').mouseover(function() {
		if ($(this).find('input').attr('disabled') != true) {
			$(this).addClass('active');
		}
	}).mouseout(function() {
		if ($(this).find('input').attr('checked') == false) {
			$(this).removeClass('active');
		}
	});
	$('.extendedLicenseRow').mouseover(function() {
		if ($(this).find('input').attr('disabled') != true) {
			$(this).addClass('active');
		}
	}).mouseout(function() {
		if ($(this).find('input').attr('checked') == false) {
			$(this).removeClass('active');
		}
	});
	
	
	// Send "download" form
		// a) show modal window of buy photo
		// b) start downloading image 
	$('#buyFormSubmit').click(function() {
		try {
			var sizeId 		= $('#buyFormSizeID').val();
			var priceId 	= $('#buyFormPriceID').val();
			var hash 			= $('#buyFormHash').val();
			var price 		= $('#buyFormPrice').val();
			var credits 	= $('#buyFormCredits').val();
			var purchased = $('#buyFormPurchased').val();
			var promocode = $('#buyFormPromocode').val();
			var guarantee = $('#buyFormLegalGuarantee').val();
			var downloadable = ((hash != '' && hash != 'NONE') ? true : false);
			
			if (sizeId != '' && priceId != '') {
				if (typeof(isFreeImage) !== 'undefined' && isFreeImage == '1') {
				
					downloadFreeImage(objekt, sizeId, priceId, hash);
					return false;
					
				} else if (typeof(editorialContent) !== 'undefined' && editorialContent == '1') {
				
					if ((downloadable == true && isAuthed == true) || purchased == 'YES') {
						if (imageKindBalance >= parseFloat(credits) || purchased == 'YES') {
							downloadEditorialImage(objekt, sizeId, priceId, hash, 1, price);
						} else {
							downloadEditorialImage(objekt, sizeId, priceId, hash, 0, price);
						}
					} else {
						downloadEditorialImage(objekt, sizeId, priceId, hash, 0, price);
					}
					return false;
					
				} else if ((imageKindBalance >= parseFloat(credits)) || (purchased == 'YES')) {
				
				  try { trackGoal('/funnel_G1/step1.html'); } catch (e) {}
				  downloadImage(objekt, sizeId, priceId, hash, promocode, '');
					return false;
					
				} else {
					return buy_photo_modal(objekt, sizeId, priceId, hash, price, promocode, guarantee);
				}
			} else {
				alert(buyFormEmptyMsg);
			}
		} catch (e) {
			alert(e);
		}
		return false;
	});
	
	// Click on extended licenses in extended options
	$('.extendedLicenseRow').click(function() {
		var input = $(this).find('input');
		if (input.attr('disabled') != true) {
			$('.priceRow').removeClass('active');
			$('.extendedLicenseRow').removeClass('active');
			$('.priceRow').each(function() {
				$(this).find('input').attr('checked', false);
			});
			$('.extendedLicenseRow').each(function() {
				$(this).find('input').attr('checked', false);
			});
			input.attr('checked', true);
			$(this).addClass('active');
			recountTotalPrice();
			updateBuyForm(input);
			updateBuyCreditsPercent();
		}
		recountTotalPrice();
	});
/*
	$('.extendedLicenseRow input').click(function() {
		$('.extendedLicenseRow').removeClass('checked');
		if ($(this).parent().parent().attr('disabled') != true) {
			if ($(this).attr('checked') == true) {
			
				if ($(this).attr('license') == 'extended') {
					$('.priceRow .radio').attr('disabled', true);
				} else {
					$('.priceRow .radio').attr('disabled', false);
				}
				
				// Check full-size
				$('.priceRow').removeClass('active');
				var fullsizeInput = $('#' + fullsizeId);
				fullsizeInput.attr('checked', true);
				fullsizeInput.attr('disabled', false);
				fullsizeInput.parent().parent().addClass('active');
				recountTotalPrice();
				updateBuyForm(fullsizeInput);
				updateBuyCreditsPercent();
					
				$(this).parent().parent().addClass('checked');
			} else {
				$(this).parent().parent().removeClass('checked');
			}
		}
		recountTotalPrice();
		updateBuyForm($(this));
	});
*/	
	
	// Click on extended option in extended options
	$('.extendedPriceRow input').click(function() {
		if ($(this).parent().parent().attr('disabled') != true) {
			if ($(this).attr('checked') == true) {
				$(this).parent().parent().addClass('checked');
			} else {
				$(this).parent().parent().removeClass('checked');
			}
		}
		recountTotalPrice();
		updateBuyForm($(this));
		
		if ($('input[name=legalGuarantee]').attr('checked') === true) {
			$('#buyFormLegalGuarantee').val(1);
		} else {
			$('#buyFormLegalGuarantee').val(0);
		}
		
	});
	
	
	
				
});




