var lastPhoto = "";
photos2show = new Array();
photos2fit = new Array();
var idPh2Fit = 0;
$(document).ready(function(){
	if (!isMobile) $('.scroll-pane').jScrollPane();
	startFit(false);
	setTimeout("checkScroll()",5000);
	setupSearch();
	$('#searchFilters').change(function() {
	  pushSearch();
	});
	$('#searchInput').keyup(function() {
	  pushSearch();
	});
	fitVideo();
});

$(function()
			{
				if (!isMobile) $('.scroll-pane').jScrollPane();
			});

$(window).resize(function() {
	startFit(true);
	if (currentDetailImg > -1) imageDetail(currentDetailImg);	
});
function checkScroll() {
	if (!isMobile) $('.scroll-pane').jScrollPane();
	//setTimeout("checkScroll()",10000);
}

function fitVideo() {
	if ($("#videoHolder").length > 0) {
		var relacionVideo = 398/224;
		var relacionVideoInversa = 224/398;
		var relacionActual = $("#videoHolder").width()/$("#videoHolder").height();
		//alert(relacionVideo + " " + relacionActual +"\n"+$("#videoHolder").width() + " " + $("#videoHolder").height());
		/*
		var relacionVideo = 224/398;
		$("#videoHolder").height($("#videoHolder").width()*relacionVideo);
		if ($("#videoHolder iframe").length > 0 && $("#videoHolder iframe").position().bottom > $(window).height()) {
			relacionVideo = 398/224;
			$("#videoHolder").height("100%");
			$("#videoHolder").width($("#videoHolder").height()*relacionVideo);
		}*/
		$("#videoHolder").css('width',$("#content").width());
		$("#videoHolder").css('height',$("#videoHolder").height() +($(window).height()- ($("#videoHolder").position().top + $("#videoHolder").height())));
		//alert($("#videoHolder").height() +($(window).height()- ($("#videoHolder").position().top + $("#videoHolder").height())));
		/*
		if (relacionVideo < relacionActual) {
			alert(1);
			$("#videoHolder").height( $("#videoHolder").height() +($(window).height()- ($("#videoHolder").position().top + $("#videoHolder").height())));
			$("#videoHolder").width($("#videoHolder").height()*relacionVideo);
		} else {
			alert(2);
			$("#videoHolder").width($("#content").width());
			$("#videoHolder").height($("#content").width()*relacionVideoInversa);
		}*/
		$("#videoHolder iframe").height($("#videoHolder").height());
		$("#videoHolder iframe").width($("#videoHolder").width());
	}	
}

function startFit(fromResize) {
	fitVideo();
	if ($("#contentDataDetail").length > 0) $("#contentDataDetail").height($(window).height()-85);
	if ($(".scrollable").length > 0) $(".scrollable").height($(window).height());
	if ($(".scrollable-wo-footer").length > 0) $(".scrollable-wo-footer").height($(window).height()-20);
	
	if ($("#oneartist").length > 0) $("#oneartist").height($(window).height()-19);	
	if ($(".contentDataPhotos").length > 0) $(".contentDataPhotos").height($(window).height()-80);	
	if ($(".contentDataPhotosWVideo").length > 0) $(".contentDataPhotosWVideo").height($(window).height()-410);	
	if ($(".scrollableType1").length > 0) {
		if ($(".scrollableType1").height() > $(window).height()/2-30) {			
			$(".scrollableType1").height($(window).height()/2-30);
		}
		if ($("#artistsList").length > 0) $("#artistsList").height($(window).height() - $(".latestWork").height()-500 );
		$(".scrollableType2").height($(window).height()-$(".scrollableType1").height()-103);
	}
	if (!isMobile && $(".scrollableType3").length > 0) $(".scrollableType3").height($(window).height()-49);
	if ($(".scrollCompany").length > 0) $(".scrollCompany").height($(window).height()-178);
	if ($(".filldown").length > 0) $(".filldown").height($(window).height());
	fitPhotos(fromResize);
	if (isMobile) {
		$("#innerList").width($(window).width()-$(".col1").width());
		$("#innerListList").width($("#innerList").width());
		$("#innerList .newscontent").width($("#innerListList").width()-17);
		$("#innerList div.newsLine").width($("#innerListList").width()-18);
		$(".latestWorkLine").width($(window).width()-$(".col1").width()-15);
		$("#latestWork").width($(window).width()-$(".col1").width());
		$("#production").width($(window).width()-$(".col1").width());
		$("#production .workList").width($(window).width()-$(".col1").width());
		if ($(window).width() < 400) {
			$("#content").width(320);
		}
		// #innerListList, #innerList
	}
	if (!isMobile) $('.scroll-pane').jScrollPane();
}

function fitPhotos(fromResize) {
	if (lastPhoto == "") return;
	var lastPhoto_fila = lastPhoto.substring(lastPhoto.indexOf("_")+1, lastPhoto.lastIndexOf("_"));
	var lastPhoto_idx = lastPhoto.substring(lastPhoto.lastIndexOf("_")+1);
	ask4fit(fromResize);
	callAgain = false;
	for (i = 0; i < lastPhoto_fila+1; i++) {
		for (j = 0; j < 5; j++) {
			if ($("#img_"+i+"_"+j).length == 0 || $("#img_"+i+"_"+j).width() == 0) {
				// voy a pedir que vuelva a llamar al fitPhotos en un ratito:
				callAgain = true;
				break;
			}
		}
	}
	if (callAgain) setTimeout("fitPhotos("+fromResize+")",1000);
	checkScroll();
}

var fitting = false;
var asked4fit = false;
function ask4fit(fromResize) {
	if (fitting) {
		asked4fit = true;
		return;
	}
	fitting = true;
	do {
		asked4fit = false;
		fitAllPhotos(fromResize);
		//$("#photoHolder a img").each(function() { if ($(this).width() > 0) fitPhoto(this,fromResize); });
	} while(asked4fit); // if somebody asked for fit while fitting...
	fitting = false;
}

function fitAllPhotosPorPorcentaje(fromResize) /* con porcentaje */
{
	fromResize = false;
	if (fromResize) return;
	var lastrow = lastPhoto.substring(lastPhoto.indexOf("_")+1, lastPhoto.lastIndexOf("_"));
	for (fila=0; fila < lastrow+1; fila++) {
		var maxH = 128;
		// primero ubico en esa fila al de menor altura:
		var minH = 1000;
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0 || compObj.height() == null || compObj.height() == 0) continue;
			minH = Math.min(compObj.height(), minH);
			//compObj.css("paddingLeft", 0);
		}
		minH = Math.min(maxH, minH);

		// ahora rehago la altura de todos para esto:
		var totalWidth = 0;
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0 || compObj.height() == null || compObj.height() == 0) continue;
			compObj.css("height", minH);
			compObj.css("width", "auto");
			totalWidth += compObj.width();
		}
		// ahora vamos reduciéndolas para que entren en el photoHolder
		var size2match = $("#photoHolder").width()-(fromResize?6:2);
		
		// alert(currentWidth + " " + totalWidth);
		// 
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0 || compObj.height() == null || compObj.height() == 0) continue;
			//compObj.height(compObj.height()*size2match/totalWidth);
			//alert(totalWidth/compObj.width());
			compObj.width((100/totalWidth*compObj.width())+"%");
			compObj.height("auto");
		}
		
	}
}

function fitAllPhotos(fromResize) /* por tamaño */
{
	fromResize = false;
	var lastrow = lastPhoto.substring(lastPhoto.indexOf("_")+1, lastPhoto.lastIndexOf("_"));
	for (fila=0; fila < lastrow+1; fila++) {
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0) continue;
			compObj.css("height", "auto");
			compObj.css("width", "auto");
		}
		var maxH = 128;
		// primero ubico en esa fila al de menor altura:
		var minH = 1000;
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0 || compObj.height() == null || compObj.height() == 0) continue;
			minH = Math.min(compObj.height(), minH);
			//compObj.css("paddingLeft", 0);
		}
		minH = Math.min(maxH, minH);

		// ahora rehago la altura de todos para esto:
		var currentWidth = 0;
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0 || compObj.height() == null || compObj.height() == 0) continue;
			compObj.css("height", minH);
			compObj.css("width", "auto");
			currentWidth += compObj.width();
		}
		// ahora vamos reduciéndolas para que entren en el photoHolder
		var userAgent = navigator.userAgent.toLowerCase();
		var msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );
	//	alert(msie);
		var size2match = $("#photoHolder").width()-(msie?32:12); //(fromResize?12:12);
		//var size2match = $("#photoHolder").width()-12; //(fromResize?12:12);
		
		// ahora comprobamos el ancho total:
		var totalWidth = 0;
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0 || compObj.height() == null || compObj.height() == 0) continue;
			totalWidth += compObj.width();
		}
		// 
		for (var i = 0; i < 5; i++) {
			var compObj = $("#img_"+fila+"_"+i);
			if (compObj.length == 0 || compObj.height() == null || compObj.height() == 0) continue;
			compObj.height(compObj.height()*size2match/totalWidth);
		}
		
	}
}

function closeSubMenu() {
	window.location = "/";
	
}

function closeSubMenuPhotographer() {
	window.location = "photographers.php";
}

function closeSubMenuTalent() {
	window.location = "talents.php";
}

function closeSubMenuBlogger() {
	window.location = "bloggers.php";
}


function closeSubMenuNoticias() {
}

function togglePhotos() {
	$("#photoHolder").slideToggle();
}

function toggleVideo() {
	$("#videoHolder").slideToggle();
}

var currentImageDetail;
var photoDetailPool = new Array();
var currentDetailImg = -1;
var lastBackBtLink = "";
function imageList() {
	$(".theBackBtn").attr("href",lastBackBtLink);
	$("#contentDataDetail").fadeOut();
	$("#contentDataList").fadeIn();
}

function imageDetail(id) {
	if ($("#"+id).length == 0) return;
	currentDetailImg = id;
	lastBackBtLink = $(".theBackBtn").attr("href");
	$(".theBackBtn").attr("href","javascript:imageList();");
	$("#contentDataDetail").fadeIn();
	$("#contentDataList").fadeOut();
	$("#contentDataDetailHolder").children().each(function() {
		$(this).attr("src", $(this).attr("src").replace("size0", "original")); 
	});
	var posDestino = 0;
	var filaori = currentDetailImg.substring(currentDetailImg.indexOf("_")+1, currentDetailImg.lastIndexOf("_"));
	var idxori = currentDetailImg.substring(currentDetailImg.lastIndexOf("_")+1);
	var fila = 0;
	var idx = 0;
	while (true) {
		var obj = $("#detail_img_"+fila+"_"+idx);
		if (obj.length == 0 || (fila == filaori && idx == idxori)) break;		
		posDestino += obj.width()+4;
		$("#number_img_"+fila+"_"+idx).removeClass("imgNumberListSelected");
		//alert(posDestino + " " + fila + " " + filaori + " "+idx + " " +idxori);
		if (idx == 4) {
			fila++;
			idx=0;
		} else {
			idx++;
		}
	}
	$("#contentDataDetailHolder").animate({
		left: -posDestino
	}, 500);
	$("#number_"+id).addClass("imgNumberListSelected");
}

function previousImg() {
	var fila = currentDetailImg.substring(currentDetailImg.indexOf("_")+1, currentDetailImg.lastIndexOf("_"));
	var idx = currentDetailImg.substring(currentDetailImg.lastIndexOf("_")+1);
	if (idx == 0 && fila == 0) return;
	else if (idx == 0) {
		fila--;
		idx=4;
	} else {
		idx--;
	}
	if ($("#img_"+fila+"_"+idx).length == 0) return;
	imageDetail("img_"+fila+"_"+idx);
	//$("#detail_img").fadeOut(500, function() {imageDetail("img_"+fila+"_"+idx);});
}

function nextImg() {
	var fila = currentDetailImg.substring(currentDetailImg.indexOf("_")+1, currentDetailImg.lastIndexOf("_"));
	var idx = currentDetailImg.substring(currentDetailImg.lastIndexOf("_")+1);
	if (idx == 4) {
		fila++;
		idx=0;
	} else {
		idx++;
	}
	if ($("#img_"+fila+"_"+idx).length == 0 || $("#img_"+fila+"_"+idx).attr('src') =='/img/pixelGrande.gif') return;
	imageDetail("img_"+fila+"_"+idx);
	//$("#detail_img").fadeOut(500, function() {imageDetail("img_"+fila+"_"+idx);});
}

function changeIdioma(lang) {
	document.location = changeWindowLanguaje(document.location.href, lang);
}

function changeWindowLanguaje(url, idioma) {
	str = url;
	
	re = /\?lang=..\&/g; 
	str = str.replace(re,"?");

	re = /(\?l|\&l)ang=../g;
	str = str.replace(re, "");

	if (str.indexOf('?')>0) 
		str = str + "&lang=" + idioma;
	else
		str = str + "?lang=" + idioma;
	return str;
}

function slideToggle(id) {
	$("#"+id).toggle();
}

function hideShow(obj) 
{
	obj.toggle('slide');
}

function sndM(obj) {
	var result = $.ajax({
	  url: "SendMail.php",
	  type: "POST",
	  data: ({
		senderName  : $("#"+obj+"name").val(),
		senderEmail : $("#"+obj+"mail").val(),
		emailMessage : $("#"+obj+"msj").val(),
		area : $("#"+obj+"area").val(),
		phone : $("#"+obj+"phone").val(),
		country : $("#"+obj+"cntry").val(),
		city : $("#"+obj+"city").val(),
		dst : (obj == "cMAD")?"MAD":"BCN"
	  }),
	  async: false,
      success: function(msj0) {
		alert(msj0)
	  },
	  fail: function(msj0,msj1,msj2) { alert("Fail!\n"+msj0+"\n"+msj2+"\n"+msj2) }
	 });	
}

function suggest() {
	var obj = "suscribeForm";
	var result = $.ajax({
	  url: "suggest.php",
	  type: "POST",
	  data: ({
		senderName  : $("#suggestname").val(),
		receiverEmail : $("#suggestemail").val()
	  }),
	  async: false,
      success: function(responseData) {

		data = $.parseJSON(responseData);
		alert(data.message)
	  },
	  fail: function(msj0,msj1,msj2) { alert("Fail!\n"+msj0+"\n"+msj2+"\n"+msj2) }
	 });	
}

function suscribe() {
	var obj = "suscribeForm";
	var result = $.ajax({
	  url: "subscribe.php",
	  type: "POST",
	  data: ({
		senderName  : $("#suscribeFormname").val(),
		senderEmail : $("#"+obj+"mail").val(),
		emailMessage : $("#"+obj+"msj").val(),
		area : $("#"+obj+"area").val(),
		phone : $("#"+obj+"phone").val(),
		country : $("#"+obj+"cntry").val(),
		city : $("#"+obj+"city").val(),
		comments : $("#"+obj+"comments").val(),
		accept : $("#suscribeFormterms").is(':checked')?"1":"0"
	  }),
	  async: false,
      success: function(responseData) {

		data = $.parseJSON(responseData);
		if (data.status == "OK")
		{
			h = $("#suscribeForm").height();
			$("#suscribeForm").html(data.message);
			$("#suscribeForm").height(h);
		} else alert(data.message)
	  },
	  fail: function(msj0,msj1,msj2) { alert("Fail!\n"+msj0+"\n"+msj2+"\n"+msj2) }
	 });	
}

function unsuscribe() {
	var result = $.ajax({
	  url: "unsubscribe.php",
	  type: "POST",
	  data: ({
		senderEmail : $("#unsuscribeFormEmail").val()
	  }),
	  async: false,
      success: function(msj0) {
		alert(msj0)
	  },
	  fail: function(msj0,msj1,msj2) { alert("Fail!\n"+msj0+"\n"+msj2+"\n"+msj2) }
	 });	
}

function swap(obj) {
	$("#"+obj).toggle();
}

function companySwap(obj0, obj1, obj2) {
	$("#"+obj0).show();
	$("#"+obj1).hide();
	$("#"+obj2).hide();
	if (!isMobile) $('.scroll-pane').jScrollPane();
}

function openSearch() {
	//$("#menuitems").css("height","283px");
	$(".col2").hide();
	$(".col3").hide();
	$("#colSearch").show();
	$("#searchContainer").show();
	pushSearch();
}

function closeSearch() {
	//$("#menuitems").css("height","100%");
	$(".col2").show();
	$(".col3").show();
	$("#colSearch").hide();
	$("#searchContainer").hide();
}

function pushSearch() {
	var result = $.ajax({
	  url: "search.php",
	  type: "POST",
	  data: ({
		searchText  : $("#searchInput").val(),
		searchFilter : $("#searchFilters :selected").val()
		// aqui van tambien las secciones sobre las que se acota
	  }),
	  async: true,
      success: function(msj0) {
		populateSearch(msj0)
	  },
	  fail: function(msj0,msj1,msj2) { alert("Fail!\n"+msj0+"\n"+msj2+"\n"+msj2) }
	 });	
}

function populateSearch(responseData) {
	data = $.parseJSON(responseData);
	//
	$("#resultsSize").html(data.resultSize);
	// resultBox
	$("#resultPhotographersBox").html("");
	$("#resultVideographersBox").html("");
	$("#resultBloggersBox").html("");
	$("#resultTalentersBox").html("");
	$("#resultArtDirectionBox").html("");
	$("#resultGraphicDesignBox").html("");
	$("#resultIllustrationBox").html("");
	$("#resultPostProductionBox").html("");
	$("#resultMultimediaBox").html("");
	$("#resultProductionBox").html("");
	populateArtists($("#resultPhotographersTitle"), $("#resultPhotographersBox"), data.photographers, 0);
	populateArtists($("#resultVideographersTitle"), $("#resultVideographersBox"), data.videographers, 1);
	populateArtists($("#resultBloggersTitle"), $("#resultBloggersBox"), data.bloggers, 2);
	populateArtists($("#resultTalentersTitle"), $("#resultTalentersBox"), data.talenters, 3);
	//
	populateCategory($("#resultProductionTitle"), $("#resultProductionBox"), data.works, 1);
	populateCategory($("#resultIllustrationTitle"), $("#resultIllustrationBox"), data.works, 2);
	populateCategory($("#resultArtDirectionTitle"), $("#resultArtDirectionBox"), data.works, 3);
	populateCategory($("#resultPostProductionTitle"), $("#resultPostProductionBox"), data.works, 4);
	populateCategory($("#resultGraphicDesignTitle"), $("#resultGraphicDesignBox"), data.works, 5);
	populateCategory($("#resultMultimediaTitle"), $("#resultMultimediaBox"), data.works, 6);
	//$("#resultBox").html(responseData);
}

function populateArtists(objTitle, objResultBox, data, type) {
	if (data != null && data.length > 0) {
		objTitle.show();
		objResultBox.show();
		for (i = 0; i < data.length; i++) {
			objResultBox.append(resolveArtistUrl(type, data[i]));
		}
	} else {
		objTitle.hide();
		objResultBox.hide();
	}
}

function populateCategory(objTitle, objResultBox, dataWorks, type) {
	if (dataWorks == null) {
		objTitle.hide();
		objResultBox.hide();
		return;
	}
	var data = new Array();
	for (i = 0; i < dataWorks.length; i++) {
		if (
			(type == 1 && dataWorks[i].blSection1 == 1) ||
			(type == 2 && dataWorks[i].blSection2 == 1) ||
			(type == 3 && dataWorks[i].blSection3 == 1) ||
			(type == 4 && dataWorks[i].blSection4 == 1) ||
			(type == 5 && dataWorks[i].blSection5 == 1) ||
			(type == 6 && dataWorks[i].blSection6 == 1)
			) data.push(dataWorks[i]);
	}
	
	
	if (data.length > 0) {
		objTitle.show();
		objResultBox.show();
		for (i = 0; i < data.length; i++) {
			objResultBox.append(resolveCategoryUrl(type, data[i]));
		}
	} else {
		objTitle.hide();
		objResultBox.hide();
	}
}

function resolveCategoryUrl(type, data) {
	seccion = "pp";
	result = '<a href="productionWork.php?ty='+seccion+'&idW='+data.idWork+'"><div class="newsLine"><div class="newstools">';
	if (data.stIdVimeo != "") result += '<img src="img/ico-video.gif" />';
	if (data.photos != "") result += '&nbsp;<img src="img/ico-foto.gif" />';
	result += '</div><div class="newscontent"><div class="latestWorkText">';
	result += '<h1>'+data.stName+'</h1> <h2>'+(idioma_session=="ES"?data.stDesc:data.stDescEng)+'</h2><br>';
	result += '<h3>';
	if (data.categories != undefined) result += data.categories;
	result += '</h3>';
	result += '</div></div></div></a>';
	return result;
}

function resolveArtistUrl(type, data) {	
	url = "";
	switch(type) {
		case 3:
			url = "talenter.php?idA="+data.idTalenter+"&ty=0";
			break;
		case 2:
			url = "blogger.php?idA="+data.idBlogger+"&ty=0";
			break;
		case 1:
			url = "videographer.php?idA="+data.idVideographer+"&ty=0";
			break;
		case 0:
			url = "photographer.php?idA="+data.idPhotographer+"&ty=0";
			break;
	}
	result = "";
	result += '<a href="'+url+'">';
	result += '<div class="newsLine"><div class="newstools">';
	if (data.stIdVimeo != "") result += '<img src="img/ico-video.gif" />';
	if (data.photos != "") result += '&nbsp;<img src="img/ico-foto.gif" />';
	result += '</div><div class="newscontent">';
	result += '<h1>'+(data.stName!=null?data.stName:"")+'</h1><h2>'+(data.stSurname!=null?data.stSurname:"")+'</h2><br>';
	result += '<h3>';
	if (data.categories != undefined) result += data.categories;
	result += '</h3>';
	result += '</div></div>';
	result += '</a>';
	
	return result;
}

function setupSearch() {
	$("#resultPhotographersTitle").hide(); 
	$("#resultPhotographersBox").hide(); 
	$("#resultVideographersTitle").hide(); 
	$("#resultVideographersBox").hide(); 
	$("#resultBloggersTitle").hide(); 
	$("#resultBloggersBox").hide(); 
	$("#resultTalentersTitle").hide(); 
	$("#resultTalentersBox").hide(); 
	
	$("#resultArtDirectionTitle").hide(); 
	$("#resultArtDirectionBox").hide(); 
	$("#resultGraphicDesignTitle").hide(); 
	$("#resultGraphicDesignBox").hide(); 
	$("#resultIllustrationTitle").hide(); 
	$("#resultIllustrationBox").hide(); 
	$("#resultPostProductionTitle").hide(); 
	$("#resultPostProductionBox").hide(); 
	$("#resultMultimediaTitle").hide(); 
	$("#resultMultimediaBox").hide(); 
	$("#resultProductionTitle").hide(); 
	$("#resultProductionBox").hide(); 
}
