var mouseisover=false;
var to;
$(document).ready(function() {
  // $(document).pngFix();

   $(".thumbnail_box").hover( function() {
	   mouseisover=true;
	   clearTimeout(to);
       var id = $(this).attr("id").replace("thumbnail-","");
       updatebtn_addremovefrombasketthumb(id);
       $("#download-original").attr("href", "download.php?id="+id);
       $("#thumbnail_infobox .thumbnail_infobox_link").attr("href", "preview.php?id="+id);
       $("#thumbnail_infobox_online").attr("href", "download.php?id="+id+"&quality=online");
       $("#thumbnail_infobox_print").attr("href", "download.php?id="+id+"&quality=original");
       $("#thumbnail_infobox_add").attr("href", "add.php?id="+id);
       $("#thumbnail_infobox_image").attr("src", $(this).find('.gimg').attr('src'));
       $("#thumbnail_infobox_title").html($(this).find('.thumbnail_box_title a').html());
       $("#btn_addremovefrombasket").unbind().click(function() {
       		return addRemoveFromBasketThumb(id);
       });
       var pos = $(this).offset();
       var eWidth = $(this).outerWidth();
       var mWidth = $('#thumbnail_infobox').outerWidth();
       var left = (pos.left + eWidth - mWidth + 18) + "px";
       var top = pos.top-20 + "px";
       
       $("#thumbnail_infobox").css({top:top, left:left}).show();
   });
   
    $("select.changesize").change( function() {
       	var id = $(this).attr("id").replace("changesize-","");
       	var v = $(this).find(':selected').val().split(":");
       	$("#filesize-"+id).text( v[1]);
       	
       	var total = 0;
       	$(".filesize").each( function() {
       		total+=parseFloat($(this).text());
       	});
       	
       	total = parseInt(total*100)/100;
       	
       	$("#filesize-total").text(total+' MB');
       	
       	$.get('dfchangeversion.php?id='+id+'&version='+v[0]);
       });
   
   $("#thumbnail_infobox").hover( function() {}, function() {
   		to = setTimeout(checkhover, 1000);
   });
   
   $(".download_folder_compare_link").click( function() {
   		var nr = 0;
   		$(".download_basket_row").each( function() {
       		var v = ($(this).attr("id").split("-"));
       		var id = v[1];
       		var exist = $("#clonebox-"+id).length;
       		if (exist<1) {
	       		var box = $("#comparebox").clone().attr("id","clonebox-"+id).insertBefore($("#comparebox"));
	       		box.find(".comparebox_title").text($(this).find('.download_basket_row_title').text());
	       		box.find(".comparebox_id").text(id);
	       		box.find(".comparebox_remove").click( function() {
	       			addRemoveFromBasketFolder(id);
	       			box.remove();
	       		});
	       		box.find(".comparebox_close").click( function() {
	       			box.remove();
	       			
	       			var nr=0;
	       			$(".comparebox").each(function(i, item) {
				  		nr++;
				  	});
					
				  	//om terms eller user guide �r framme s� ska inte showMediaType k�ras
				  	if ((nr<=1) && (userGuideTermsStatus()==false)) {
				  		showMediaType();
				  		$(".changesize").css("visibility","visible");
				  	} 
	       		});
	       		var el=$(this).find(".download_basket_row_bigimg img");
	       		var bigimg = el.attr("src");
	       		var bigstyle = el.css();
	       		
	       		box.find(".comparebox_download_online").attr("href","download.php?id="+id+"&quality=online");
	       		box.find(".comparebox_download_print").attr("href","download.php?id="+id+"&quality=original");
	       		box.find(".gimg").css('height',bigstyle.css('height'));
	       		box.find(".gimg").css('width',bigstyle.css('width'));
	       		box.find(".gimg").attr("src",bigimg);
				
				var left=nr*40+100;
				var top=nr*10+100;
				nr++;
				
	       		showCompare(box, left, top);
	       	}
	       	
	       	hideMediaType();
	       	
	       	//g�mma alla select print/online
	       	$(".changesize").css("visibility","hidden");
	       	
	       	//$("#backgroundPopup").css({"opacity": "0.5"});  
			//$("#backgroundPopup").show();
       	});
   });
   
   $("#user_guide").hide();
});

function userGuideTermsStatus() {
	if ($("#user_guide").css('display')=="block")
		return true;
	else if ($("#termsbox").css('display')=="block")
		return true;
	else
		return false;
}

function checkhover() {
	$("#thumbnail_infobox").hide();
}

function showCompare(box, left, top) {
	box.css({top:top, left:left}).css('z-index', 100).show();
	$.extend($.ui.draggable.prototype, (function (orig) {
		  return {
		    _mouseCapture: function (event) {
		      var result = orig.call(this, event);
		      if (result && $.browser.msie) event.stopPropagation();
		      return result;
		    }
		  };
		})($.ui.draggable.prototype["_mouseCapture"]));

	box.draggable({
	  start: function() { $(this).appendTo('body'); },
	//  zIndex: 1000,
	  stop: function() { 
	  	$(".comparebox").css("zIndex",100);
	  	$(".comparebox").each(function(i, item) {
	  		$(this).css('zIndex',100);
	  	}); 
	  	
	  	//ger �ven terms och user guide zIndex 100
	  	$("#termsbox").css("zIndex", 100);
	  	$("#user_guide").css("zIndex", 100);
	  	
	  	$(this).css("zIndex",200); }
	});
	
	box.click( function () {
		$(".comparebox").css("zIndex",100);
	  	$(".comparebox").each(function(i, item) {
	  		$(this).css('zIndex',100);
	  	});
	  	
	  	//ger �ven terms och user guide zIndex 100
	  	$("#termsbox").css("zIndex", 100);
	  	$("#user_guide").css("zIndex", 100);
	  	
	  	$(this).css("zIndex",200);
	});
}

function hideMediaType() {
	$("#mediatype").css("visibility", "hidden");
}

function showMediaType() {
	$("#mediatype").css("visibility", "visible");
}

function showUserGuide() {
	$("#user_guide").css({top:150, left:150}).css("zIndex", 100).show();
	$("#user_guide").draggable({handle: 'h1',
		zIndex: 1000,
	  	stop: function() { 
		  	$(".comparebox").css("zIndex",100);
		  	$(".comparebox").each(function(i, item) {
		  		$(this).css('zIndex',100);
		  	});
		  	
		  	//ger �ven terms zIndex 100
		  	$("#termsbox").css("zIndex", 100);
		  	
		  	$("#user_guide").css("zIndex",200); 
		}
	});
	
	$("#user_guide").click( function () {
		$(".comparebox").css("zIndex",100);
	  	$(".comparebox").each(function(i, item) {
	  		$(this).css('zIndex',100);
	  	});
	  	
	  	//ger �ven terms zIndex 100
	  	$("#termsbox").css("zIndex", 100);
	  	
	  	$("#user_guide").css("zIndex",200);
	});
	
	hideMediaType();
	
	//�ven g�mma kategorierna i advanced search om de �r framme
	$(".category-level").css("visibility", "hidden");
	
	//och g�mma download folder-selects
	$(".changesize").css("visibility","hidden");
}

function hideUserGuide() {
	$("#user_guide").hide();
	
	//visa selectboxar om inte terms syns, eller compare-rutor
	var nr=0;
    $(".comparebox").each(function(i, item) {
  		nr++;
  	});
	
  	//om terms eller user guide �r framme s� ska inte showMediaType k�ras
  	if ((nr<=1) && (userGuideTermsStatus()==false)) {
  		showMediaType();
  		$(".changesize").css("visibility","visible");
  		
  		//adv search
  		$(".category-level").css("visibility", "visible");
  	}
}

function showTerms() {
	$("#termsbox").css({top:150, left:150}).show();
	$("#termsbox").draggable({handle: 'h1'});
	hideMediaType();
	
	//�ven g�mma kategorierna i advanced search om de �r framme
	$(".category-level").css("visibility", "hidden");
	
	//och g�mma download folder-selects
	$(".changesize").css("visibility","hidden");
}

function hideTerms() {
	$("#termsbox").hide();
	
	//visa selectboxar om inte terms syns, eller compare-rutor
	var nr=0;
    $(".comparebox").each(function(i, item) {
  		nr++;
  	});
	
  	//om terms eller user guide �r framme s� ska inte showMediaType k�ras
  	if ((nr<=1) && (userGuideTermsStatus()==false)) {
  		showMediaType();
  		$(".changesize").css("visibility","visible");
  		
  		//adv search
  		$(".category-level").css("visibility", "visible");
  	}
}

var currentLevel = 0;
function getSubCategories(element) {
	var folderId = element.value;
	var $me = $(element);
	var level = $me.attr('name').replace('category-level-','');
	currentLevel = level;
	$('#folderid').val(folderId);
	$(".category-level").each( function() {
		if (parseInt($(this).attr('name').replace("category-level-","")) > level)
			$(this).remove();
	} );
	
	if (folderId!=0) {
		$.getJSON('getsubcategories.php?id='+folderId, function(data) {
			if (data!=null) {
				if (data.length!=0) {
					var html = '<select name="category-level-'+(currentLevel+1)+'" class="multiple category-level" size="12" onClick="getSubCategories(this)">';
					for(var i=0;i<data.length;i++) { html += '<option value="'+data[i].folderId+'">'+data[i].name+'</option>'}
					html += '</select>';
					$(html).appendTo('#category-tree');
				}
			}
		} );
	}
}

function addRemoveFromBasket(id) {
	try {
		$('#downloadfolderinfo').load('downloadfolderinfo.php', {id: id}, function() {
			updatebtn_addremovefrombasket(id);
		});
	} catch (e) { alert(e);}
	return false;
}

function updatebtn_addremovefrombasket(id) {
	if ($('#downloadfolderinfo #basket'+id).length > 0) {
		$('#btn_addremovefrombasket-'+id).text('Remove from download folder');
	} else {
		$('#btn_addremovefrombasket-'+id).text('Add to download folder');
	}
}

function addRemoveFromBasketThumb(id) {
	try {
		$('#downloadfolderinfo').load('downloadfolderinfo.php', {id: id}, function() {
			updatebtn_addremovefrombasketthumb(id);
		});
	} catch (e) { alert(e);}
	
	$("#downloadfolderinfo").load("downloadfolderinfo.php");
	
	return false;
}

function updatebtn_addremovefrombasketthumb(id) {
	if ($('#downloadfolderinfo #basket'+id).length > 0) {
		$('#btn_addremovefrombasket').text('Remove from folder');
	} else {
		$('#btn_addremovefrombasket').text('Add to folder');
	}
}

function addRemoveFromBasketFolder(id) {
	try {
		$('#downloadfolderinfo').load('downloadfolderinfo.php', {id: id}, function() {
			updatebtn_addremovefrombasketdf(id);
			$("#basketcount").html($('#downloadfolderinfo').html());
			if ($('#downloadfolderinfo div.basketitem').length == 0) {
				document.location='download_folder.php';
			}
		});
	} catch (e) { alert(e);}
	

	
	var exist = $("#clonebox-"+id).length;
	if (exist>0) {
		$("#clonebox-"+id).remove();
	}
	
	return false;
}

function updatebtn_addremovefrombasketdf(id) {
	$('#download_basket_row-'+id).remove();
	return false;
}

function updateSizes(o, id) {
	var opt = o.options[o.selectedIndex];
	var high = document.getElementById('quality-high-'+id);
	var low = document.getElementById('quality-low-'+id);
	
	high.setAttribute('size', opt.getAttribute('highsize'));
	low.setAttribute('size', opt.getAttribute('lowsize'));

	document.getElementById('filesize-'+id).innerHTML = formatSize((high.selected ? high.getAttribute('size') : low.getAttribute('size')));
}

function calculateNewTotal() {
	var totalsize = 0;
	var tds = document.getElementsByTagName('td');
	for (i=0; i<tds.length; i++) {
		if (tds[i].id.indexOf('filesize') > -1) {
			totalsize += (tds[i].innerHTML.substr(0, tds[i].innerHTML.length-3) * 1);
		}
	}
	
	document.getElementById('totalsize').innerHTML = formatSize(totalsize * 1024 * 1024);
}
