


function getimgwidth(url)
{ img = new Image();
  img.src = url;
  return img.width;
}
function getimgheight(url)
{ img = new Image();
  img.src = url;
  return img.height;
}

PopupImage = function(uri, title, maxsize) {
  imageDialog = $("#imgpopupdialog");
  imageTitle = $("#imgpopuptitle");
	imageTitle.html("<h3>"+title+"</h3>");
	imageTag = $('#imgpopupimage');
	// determin height and width of popup
	winwidth = $(window).width();
	winheight = $(window).height();
	popupw = winwidth-300; popuph = winheight-300;
	if (maxsize > 0) {
	  if (popupw > maxsize) popupw = maxsize;
	  if (popuph > maxsize) popuph = maxsize;
	}
	// resize image accordingly
	imgw = getimgwidth(uri); imgh = getimgheight(uri);
	if (imgw < imgh) ratio = popuph / imgh; else ratio = popupw / imgw;
  imgnewh = imgh*ratio;   imgneww = imgw*ratio;
  popupw = imgneww + 30;  popuph = imgnewh + 120;
  //Set the image src and size
  imageTag.attr('src', uri);  imageTag.attr('width', imgneww);  imageTag.attr('height', imgnewh);
  //When the image has loaded, display the dialog
  imageTag.load(function(){
    $('#imgpopupdialog').dialog({modal: true, resizable: false, width: popupw, height: popuph, title: title });
  });   
} // PopupImage

function showgalleryphoto(imageTag, uri) {
  imgw = getimgwidth(uri); imgh = getimgheight(uri);
	ratiow = (popupw - 30) / imgw; 	ratioh = (popuph - 150) / imgh;
	ratio = ratiow;
	if (ratioh < ratiow)
		ratio = ratioh;
	imgnewh = imgh*ratio;   imgneww = imgw*ratio;
  imageTag.attr('width', imgneww);  imageTag.attr('height', imgnewh);
	imageTag.attr('src', uri);  
}
		
		
PopupGallery = function(uri, title, galleryid, order, nrphotos, width, height) {
  imageDialog = $("#gallerypopupdialog");
  imageTitle = $("#gallerypopuptitle");
	imageTitle.html("<h3>"+title+"</h3>");
	imageTag = $('#gallerypopupimage');
	// determin height and width of popup
	winwidth = $(window).width();
	winheight = $(window).height();
	popupw = width;
	if (popupw > winwidth-300)
	  popupw = winheight-300;
	popuph = height;
	if (popuph > winheight-300)
	  popuph = winheight-300;
	showgalleryphoto(imageTag, uri);
	$("#galleryprev").click(function (event) {
      event.preventDefault();
//    	imageTag.fadeOut('fast');
      if (order>0) 
			  order--;
			else
			  return false;
  	  $.ajax({ url: 'photogallery.ajax.php?infotype=showgallery&POSTFIX='+POSTFIX+'&id='+galleryid+'&order='+order, async:false,
		  success: function(data) {
		            as2 = data.split('||');
								showgalleryphoto(imageTag, as2[0]);
					  	}
					} );
//			alert($('#gallerypopupdialog').html());
//    	imageTag.fadeIn('fast');
			return false;
	});
	$("#gallerynext").click(function (event) {
     event.preventDefault();
//   	 imageTag.fadeOut('fast');
     if (order < nrphotos-1) 
		   order++;
		 else
		   return false;
  	 $.ajax({ url: 'photogallery.ajax.php?infotype=showgallery&POSTFIX='+POSTFIX+'&id='+galleryid+'&order='+order, async:false,
		  success: function(data) {
							  as2 = data.split('||');
								showgalleryphoto(imageTag, as2[0]);
					  	}
					} );
//			alert($('#gallerypopupdialog').html());
//    	imageTag.fadeIn('fast');
			return false;
	});
	
  //When the image has loaded, display the dialog
  imageTag.load(function(){
    $('#gallerypopupdialog').dialog({modal: true, resizable: false, width: popupw, height: popuph, title: title });
  });   
} // PopupGallery

		
PopupMessage = function(title,text,popupw,popuph) {
  msgDialog = $("#msgpopupdialog");
  // determin height and width of popup
  if (popupw == 0)
    popupw = $(window).width()-200; 
  if (popuph == 0)
    popuph = $(window).height()-200;
  $('#msgpopupcontent').html(text);
  $('#msgpopupdialog').dialog({modal: true, resizable: false, width: popupw, height: popuph, title: title });
} // PopupImage

  
/* STYLES FOR POPUP DIALOG
div class="<<ui-dialog>> ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
   <div class="<<ui-dialog-titlebar>> ui-widget-header ui-corner-all ui-helper-clearfix">
      <span id="<<ui-dialog-title-dialog>>" class="ui-dialog-title">Dialog title</span>
      <a class="<<ui-dialog-titlebar-close>> ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
   </div>
   <div style="height: 200px; min-height: 109px; width: auto;" class="<<ui-dialog-content>> ui-widget-content" id="dialog">
      <p>Dialog content goes here.</p>
   </div>
</div>
*/  

function initaccordion(headerclass,contentclass) {
  // init 
	$(headerclass).show();
	$(headerclass).css("cursor","pointer");
	$(contentclass).hide();
	// on header click slide content down and op
	$(headerclass).click(function () {
		thisisclosed = $(this).next().is(':hidden') == true;
		$(contentclass+':visible').slideUp('fast');
	  if (thisisclosed)
  		$(this).next().slideDown('fast');
	});
}  

// printArea
    var printAreaCount = 0;
    $.fn.printArea = function() {
      var ele = $(this);
      var idPrefix = "printArea_";
      removePrintArea( idPrefix + printAreaCount );
      printAreaCount++;
      var iframeId = idPrefix + printAreaCount;
      var iframe = document.createElement('IFRAME');
      $(iframe).attr('style','position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
      $(iframe).attr('id', iframeId);
      document.body.appendChild(iframe);
      var doc = iframe.contentWindow.document;
      var links = window.document.getElementsByTagName('link');
      for( var i = 0; i < links.length; i++ )
          if( links[i].rel.toLowerCase() == 'stylesheet' )
              doc.write('<link type="text/css" rel="stylesheet" href="' + links[i].href + '"></link>');
      doc.write('<div class="' + $(ele).attr("class") + '">' + $(ele).html() + '</div>');
      doc.close();
      iframe.contentWindow.focus();
      iframe.contentWindow.print();
    }
    var removePrintArea = function(id) {  { $( "iframe#" + id ).remove(); }; }


function settablefieldval(tblname, id, field, val)
{
    if (tblname != "catalogus")
		  tblname += POSTFIX;
	  //  post is needed for possible '&' in content
		$.ajax({ type: 'post',   data: ({val: val}), url: 'database.ajax.php?action=set&field='+field+'&id='+id+'&tablename='+tblname, async:false, 
						 success: function(data){ /*if (data.length>0) alert(data);*/ } }
					);
}

function gettablefieldval(tblname, id, field)
{
    if (tblname != "catalogus")
		  tblname += POSTFIX;
		$.ajax({ type: 'post', url: 'database.ajax.php?infotype=get&field='+field+'&id='+id+'&tablename='+tblname, async:false, 
						 success: function(data){ result = data; } }
					);
		return result;
}

$(document).ready(function() {
	initaccordion('.acchead','.accbody');
	$('.popupimg').click(function(event){
    event.preventDefault();
    PopupImage($(this).attr('src'),$(this).attr('title'),0);
  });
  $("#printButton").click(function(){
       $("#textbox").printArea();
       return false;
    }
  );
  $("#printButtonDial").click(function(){
       $("#imgpopupcontent").printArea();
       return false;
    }
  );
  $("#printButtonGalleryDial").click(function(){
       $("#gallerypopupcontent").printArea();
       return false;
    }
  );
  $(".mainmenu").click(function(){ // select first subitem when clicking main item
       var self = $(this).parent(); // from <a> to parent <li>
	  	 document.location.href=self.children(':nth-child(2)').children(':nth-child(1)').children(':nth-child(1)').attr("href");
		   return false;
    }
  );
	$('input:checkbox') .bind("click",function(){
		content = $(this).val(); 
		as = $(this).attr('id').split('_'); // tablename_fieldname_id
		settablefieldval(as[0], as[2], as[1], $(this).is(':checked') ? 1 : 0);
	});   
	$('.tblfieldedit').bind("blur",function(){
	  if ($(this).is(':checkbox')) // see above
		  return;
		content = $(this).val(); 
		as = $(this).attr('id').split('_'); // tablename_fieldname_id or  tablename_fieldname_id_nr
		if (as.length == 4) {
		  var inputid = as[0]+'_'+as[1]+'_'+as[2];
			var j=0; var asv = new Array();
			for (i=0; i < 6; i++) {
			  var val = $('#'+inputid+'_'+i).val();
				if (val > 0)
			    asv[j++]=val;
			}
			settablefieldval(as[0], as[2], as[1], asv.join(';'));
		}	
		else 
  		settablefieldval(as[0], as[2], as[1], content);
	});   
  $(".photogal").click(function(event){
     event.preventDefault();
  	 as = $(this).attr('id').split('_'); // galeryid_order_#photos
  	 $.ajax({ type: 'post',  url: 'photogallery.ajax.php?infotype=showgallery&POSTFIX='+POSTFIX+'&id='+as[0]+'&order='+as[1], async:false, 
		          success: function(data) { 
							  as2 = data.split('||');
								PopupGallery(as2[0], as2[1],as[0], as[1],as2[2], 800, 600);
					  	}
					} );
     return false;
  });   
	$('img:[title]').click(function(event){
    event.preventDefault();
		$(this).is('.photogal')
		  return false;
    PopupImage($(this).attr('src'),$(this).attr('title'),0);
    return false;
  });
  $.fn.loadhtml = function(url) {   
      return this.each(function () {   
         var self = $(this);   
					$.ajax({ url: url, async:false, success: function(data) {
							$(self).html(data);
					}});
      });   
   };   
	$('#textbox a').click(function(event){
			var link = "";
			var href = $(this).attr('href');
			if (href.substr(0, 7).toLowerCase() == "http://") {
				link = href.substring(7);
			}
			else { 
				var as = href.split('?');
				if (as.length > 1) {
					as = as[1].split('&');
					for (i=0; i < as.length; i++) {
						if (as[i].substr(0, 5).toLowerCase() == "page=") {
							link = as[i].substring(5);
						}
					}
				}
			}
			if (link.length > 0) {
				if (link.substring(link.length-1) == "/") 
					link = link.substr(0, link.length-1);
				else if (link.substring(link.length-1) == "-") 
					link = link.substr(1, link.length-2);
				logpage(link);
			}	
			return true;
	});
 
});

function logpage(page)
{
  $.ajax({ type: "post",url: 'logging.ajax.php?logpage='+page+'&width='+window.screen.width+'&POSTFIX='+POSTFIX });
}

function trimstring(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function is_intval(value) { 
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
	    return true;
  } else { 
      return false;
  } 
}


