//jquery.leafletPXL.js
//author: 			Bjoern Sellnau @ PIXELTEX
//project:			jQuery Plugin 'LeafletPXL' - the Partnersites Version
//description:	this is the main js class for the 'Leaflet-Functionality' of Partnersites
//added:				14-08-2009
//modified:			18-03-2010
//version				0.25
//=====================================================

(function($){
	$.fn.leafletPXL = function(options)
	{
		//if current browser is FF2 on Mac abort !
		if($.fn.leafletPXL._detectMacXFF2())
		{
			$('.leaflet').css('display','none');							//hide 'open leaflet' link
			$('.leaflet_open').css('visibility','hidden');		//hide 'open leaflet' link
			$('.leaflet_link').css('visibility','hidden');		//hide 'add to leaflet' link
			
			return false;
		}
	
		//default values and properties.
		var defaults = {
			url: '/leaflet/leaflet.cfm',
			iframeClass: 'leaflet_frame',
			language: 'de',
			dragable:false,
			saveposition:false,
			savedisplay:false,
			display:'none',
			cookieActiveDays:1,
			xOffset:154,
			yOffset:26,
			xDirection:"center",
			yDirection:"top",
			openHandler:$.fn.leafletPXL.__openLeafletHandler,
			closeHandler:$.fn.leafletPXL.__closeLeafletHandler,
			addItemHandler:$.fn.leafletPXL.__addItemToLeafletHandler,
			printpdfHandler:$.fn.leafletPXL.__printPDFHandler,
			sendemailHandler:$.fn.leafletPXL.__sendemailHandler			
		};	
		var options = $.extend(defaults, options);
		
		//get position of leaflet.
		if(options.saveposition)
		{
		   	var LEAFLET_XPOS = $.fn.leafletPXL._readCookie('leaflet_xposition')||'none';
				var LEAFLET_YPOS = $.fn.leafletPXL._readCookie('leaflet_yposition')||'none';
		   	var XPOS_DIR = $.fn.leafletPXL._readCookie('leaflet_xdirection')||'none';
				var YPOS_DIR = $.fn.leafletPXL._readCookie('leaflet_ydirection')||'none';
		} else {
		   	var LEAFLET_XPOS = 'none';
				var LEAFLET_YPOS = 'none';
		   	var XPOS_DIR = 'none';
				var YPOS_DIR = 'none';
		}  

		//calculate xPosition.
		if(LEAFLET_XPOS == 'none')
		{
			if(options.xDirection == 'center')
			{
				XPOS_DIR = "left";
				var clientWidth = $(window).width();
				var halfCWidth = clientWidth/2;
				
				LEAFLET_XPOS = halfCWidth;
				if(new String(options.xOffset).indexOf('-') != -1)
				{
					LEAFLET_XPOS = LEAFLET_XPOS - String(options.xOffset).replace('-','');
				} else {
					LEAFLET_XPOS = LEAFLET_XPOS + Number(options.xOffset);		
				}
			}
			else if(options.xDirection == 'left')
			{
				XPOS_DIR = "left";
				LEAFLET_XPOS = 0;
				if(new String(options.xOffset).indexOf('-') != -1)
				{
					LEAFLET_XPOS = LEAFLET_XPOS - String(options.xOffset).replace('-','');
				} else {
					LEAFLET_XPOS = LEAFLET_XPOS + Number(options.xOffset);		
				}				
			}
			else if(options.xDirection == 'right')
			{
				XPOS_DIR = "right";
				LEAFLET_XPOS = 0;
				if(new String(options.xOffset).indexOf('-') != -1)
				{
					LEAFLET_XPOS = LEAFLET_XPOS - String(options.xOffset).replace('-','');
				} else {
					LEAFLET_XPOS = LEAFLET_XPOS + Number(options.xOffset);		
				}				
			}		
		}

		//calculate yPosition.
		if(LEAFLET_YPOS == 'none')
		{
			if(options.yDirection == 'middle')
			{
				YPOS_DIR = "top";
				var clientHeight = $(window).height();
				var halfCHeight = clientHeight/2;
				
				LEAFLET_YPOS = halfCHeight;
				if(new String(options.yOffset).indexOf('-') != -1)
				{
					LEAFLET_YPOS = LEAFLET_YPOS - String(options.yOffset).replace('-','');
				} else {
					LEAFLET_YPOS = LEAFLET_YPOS + Number(options.yOffset);		
				}
			}
			else if(options.yDirection == 'top')
			{
				YPOS_DIR = "top";
				LEAFLET_YPOS = 0;
				if(new String(options.yOffset).indexOf('-') != -1)
				{
					LEAFLET_YPOS = LEAFLET_YPOS - String(options.yOffset).replace('-','');
				} else {
					LEAFLET_YPOS = LEAFLET_YPOS + Number(options.yOffset);		
				}				
			}
			else if(options.yDirection == 'bottom')
			{
				YPOS_DIR = "bottom";
				LEAFLET_YPOS = $(window).height();
				if(new String(options.yOffset).indexOf('-') != -1)
				{
					LEAFLET_YPOS = LEAFLET_YPOS - String(options.yOffset).replace('-','');
				} else {
					LEAFLET_YPOS = LEAFLET_YPOS + Number(options.yOffset);		
				}				
			}		
		}		
	
		//get current status of leaflet.
		if(options.savedisplay)
		{
				var LEAFLET_DISPLAY = $.fn.leafletPXL._readCookie('leaflet_display')||options.display;
		} else {
		 		var LEAFLET_DISPLAY = options.display;
		}  

		//set new position and status of leaflet.
		var cssOptions = {};
		cssOptions[XPOS_DIR] = LEAFLET_XPOS;
		cssOptions[YPOS_DIR] = LEAFLET_YPOS;
		cssOptions['display'] = LEAFLET_DISPLAY;
		
		//set xDirection and yDirection.
		options.xDirection = XPOS_DIR;
		options.yDirection = YPOS_DIR;
				
		if(window.console){window.console.log(cssOptions)};

		$(".leaflet").css(cssOptions);
		$("#leaflet_frame").css('display',LEAFLET_DISPLAY);	

		//make leaflet dragable.
		if(options.dragable)
		{
			$(".leaflet").draggable({handle:'h2',stop:function(event, ui){
			    var options = $('.leaflet').data('leaflet_options');
 	        $.fn.leafletPXL._createCookie('leaflet_xposition', ui.absolutePosition.left ,options.cookieActiveDays);
 	        $.fn.leafletPXL._createCookie('leaflet_yposition', ui.absolutePosition.top ,options.cookieActiveDays);

 	        $.fn.leafletPXL._createCookie('leaflet_xdirection', options.xDirection ,options.cookieActiveDays);
 	        $.fn.leafletPXL._createCookie('leaflet_ydirection', options.yDirection ,options.cookieActiveDays);
			}});
			$(".draghandle").css('cursor','pointer');
		}

    //evaluate custom handlers
    options.openHandler = eval(options.openHandler);
    options.closeHandler = eval(options.closeHandler);
    options.addItemHandler = eval(options.addItemHandler);
    options.printpdfHandler = eval(options.printpdfHandler);
    options.sendemailHandler = eval(options.sendemailHandler);

		//call handlers.
		options.openHandler.call();
		options.closeHandler.call();
		options.addItemHandler.call();
		options.printpdfHandler.call();
		options.sendemailHandler.call();

		//add iframe		
		$('.leaflet').data('leaflet_options', options);
		var RANDOM = new Date().getTime()/1000;
		return this.each(function(){
			$('.'+options.iframeClass).append('<iframe class="leaflet_iframe" src="'+options.url+'?lang='+options.language+'&action=initlist&cache='+RANDOM+'" style="display:'+LEAFLET_DISPLAY+';" id="leaflet_frame" border="0" frameborder="0" framespacing="0" ALLOWTRANSPARENCY="true"></iframe>');		
		});
	};

	/* refreshPosition */
	$.fn.leafletPXL.render=function()
	{
		var options = $('.leaflet').data('leaflet_options');

		//get position of leaflet.
		if(options.saveposition)
		{
		   	var LEAFLET_XPOS = $.fn.leafletPXL._readCookie('leaflet_xposition')||'none';
				var LEAFLET_YPOS = $.fn.leafletPXL._readCookie('leaflet_yposition')||'none';
		   	var XPOS_DIR = $.fn.leafletPXL._readCookie('leaflet_xdirection')||'none';
				var YPOS_DIR = $.fn.leafletPXL._readCookie('leaflet_ydirection')||'none';
		} else {
		   	var LEAFLET_XPOS = 'none';
				var LEAFLET_YPOS = 'none';
		   	var XPOS_DIR = 'none';
				var YPOS_DIR = 'none';
		}  

		//calculate xPosition.
		if(LEAFLET_XPOS == 'none')
		{
			if(options.xDirection == 'center')
			{
				XPOS_DIR = "left";
				var clientWidth = $(window).width();
				var halfCWidth = clientWidth/2;
				
				LEAFLET_XPOS = halfCWidth;
				if(new String(options.xOffset).indexOf('-') != -1)
				{
					LEAFLET_XPOS = LEAFLET_XPOS - String(options.xOffset).replace('-','');
				} else {
					LEAFLET_XPOS = LEAFLET_XPOS + options.xOffset;		
				}
			}
			else if(options.xDirection == 'left')
			{
				XPOS_DIR = "left";
				LEAFLET_XPOS = 0;
				if(new String(options.xOffset).indexOf('-') != -1)
				{
					LEAFLET_XPOS = LEAFLET_XPOS - String(options.xOffset).replace('-','');
				} else {
					LEAFLET_XPOS = LEAFLET_XPOS + options.xOffset;		
				}				
			}
			else if(options.xDirection == 'right')
			{
				XPOS_DIR = "right";
				LEAFLET_XPOS = 0;
				if(new String(options.xOffset).indexOf('-') != -1)
				{
					LEAFLET_XPOS = LEAFLET_XPOS - String(options.xOffset).replace('-','');
				} else {
					LEAFLET_XPOS = LEAFLET_XPOS + options.xOffset;		
				}				
			}		
		}

		//calculate yPosition.
		if(LEAFLET_YPOS == 'none')
		{
			if(options.yDirection == 'middle')
			{
				YPOS_DIR = "top";
				var clientHeight = $(window).height();
				var halfCHeight = clientHeight/2;
				
				LEAFLET_YPOS = halfCHeight;
				if(new String(options.yOffset).indexOf('-') != -1)
				{
					LEAFLET_YPOS = LEAFLET_YPOS - String(options.yOffset).replace('-','');
				} else {
					LEAFLET_YPOS = LEAFLET_YPOS + options.yOffset;		
				}
			}
			else if(options.yDirection == 'top')
			{
				YPOS_DIR = "top";
				LEAFLET_YPOS = 0;
				if(new String(options.yOffset).indexOf('-') != -1)
				{
					LEAFLET_YPOS = LEAFLET_YPOS - String(options.yOffset).replace('-','');
				} else {
					LEAFLET_YPOS = LEAFLET_YPOS + options.yOffset;		
				}				
			}
			else if(options.yDirection == 'bottom')
			{
				YPOS_DIR = "bottom";
				LEAFLET_YPOS = $(window).height();
				if(new String(options.yOffset).indexOf('-') != -1)
				{
					LEAFLET_YPOS = LEAFLET_YPOS - String(options.yOffset).replace('-','');
				} else {
					LEAFLET_YPOS = LEAFLET_YPOS + options.yOffset;		
				}				
			}		
		}		

		var cssOptions = {};
		cssOptions[XPOS_DIR] = LEAFLET_XPOS;
		cssOptions[YPOS_DIR] = LEAFLET_YPOS;
		$(".leaflet").css(cssOptions);
	}

	/* add item to leaflet */
	$.fn.leafletPXL.addItem=function(ITEM){
	
	//alert('-')
	
		var title = $(ITEM).attr('title');

		var id_type_print = $(ITEM).attr('rel');
		id_type_print = id_type_print.split(',');
		
		var id_type = id_type_print[0];	
		var printable = id_type_print[1].split(':');
		printable = printable[1];	
				
		var url = $(ITEM).attr('href');
		id_type = id_type.split(':');
		var type = id_type[0];
		var id = id_type[1];

		var options = $('.leaflet').data('leaflet_options');

//		$('.'+$.fn.leafletPXL.options.iframeClass).attr('src',$.fn.leafletPXL.options.url+"?action=saveItem&amp;title="+title);
			//$('.'+options.iframeClass).append('<iframe id="leaflet_frame" border="0" frameborder="0" framespacing="0" ALLOWTRANSPARENCY="true"></iframe>');		
			var RANDOM = new Date().getTime()/1000;
			//$('.leaflet_frame').find(":nth-child(1)").attr('src',options.url+'?lang='+options.language+'&action=saveItem&title='+title+"&id="+id+"&type="+type+"&itemurl="+url+"&print="+printable+"&cache="+RANDOM).slideDown('fast');
			document.curr_leaflet_items++;
			$('#leaflet_frame').attr('src',options.url+'?lang='+options.language+'&action=saveItem&title='+title+"&id="+id+"&type="+type+"&itemurl="+url+"&print="+printable+"&cache="+RANDOM).slideDown('fast');

/*
			setTimeout(
			function()
			{
				var options = $('.leaflet').data('leaflet_options');
				var RANDOM = new Date().getTime()/1000;
				$('#leaflet_frame').attr('src',options.url+'?lang='+options.language+'&cache='+RANDOM).slideDown('fast');				
			},200);
*/			
			clearInterval(document.leafletRefreshInterval)
			document.leafletRefreshIntervalRun = 0
			
			document.leafletRefreshInterval = setInterval(
			function()
			{
			if(window.console){window.console.log(document.leafletRefreshIntervalRun++)};
				var options = $('.leaflet').data('leaflet_options');
				var RANDOM = new Date().getTime()/1000;
				$('#leaflet_frame').attr('src',options.url+'?lang='+options.language+'&cache='+RANDOM).slideDown('fast');				
			
				if(document.leafletRefreshIntervalRun >= 10)
				{
					clearInterval(document.leafletRefreshInterval);
					document.leafletRefreshIntervalRun = 0
				} 

			},1500);
	}

	/* get option from options */
	$.fn.leafletPXL.getOption=function(NAME)
	{
		var options = $('.leaflet').data('leaflet_options');
		return options[NAME];
	}

// ======================================================	
// utils	
$.fn.leafletPXL._createCookie=function(name,value,days) {
    
    var options = $('.leaflet').data('leaflet_options');
    if(!options.saveposition && name != 'leaflet_display'){return false}
    if(!options.savedisplay && name == 'leaflet_display'){return false}
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

$.fn.leafletPXL._readCookie=function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

$.fn.leafletPXL._eraseCookie=function(name) {
	$.fn.leafletPXL._createCookie(name,"",-1);
}	

//thanks to http://jakeo.org	
$.fn.leafletPXL._detectMacXFF2=function()
{
  var userAgent = navigator.userAgent.toLowerCase();
  if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
    var ffversion = new Number(RegExp.$1);
    if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
      return true;
    }
  }
}

$.fn.leafletPXL._closeMenu = function()
{   var options = $('.leaflet').data('leaflet_options');
 	$.fn.leafletPXL._createCookie('leaflet_xposition', $(".leaflet").css('left') ,options.cookieActiveDays);
 	$.fn.leafletPXL._createCookie('leaflet_yposition', $(".leaflet").css('top') ,options.cookieActiveDays);

  $.fn.leafletPXL._createCookie('leaflet_xdirection', options.xDirection ,options.cookieActiveDays);
  $.fn.leafletPXL._createCookie('leaflet_ydirection', options.yDirection ,options.cookieActiveDays);

	$('.leaflet').fadeOut();  	
    $.fn.leafletPXL._createCookie('leaflet_display', 'none' ,options.cookieActiveDays); 
  return false;
}

// ====================================================================================
// handlers.

//*** opens and closes the leaflet */
$.fn.leafletPXL.__openLeafletHandler=function()
{
	$('.leaflet_open').click(function()
    {
			$('#leaflet_frame').css('display','block');    
      var options = $('.leaflet').data('leaflet_options'); 
    	if($('.leaflet').css('display') == 'none')
    	{
        $('.leaflet').fadeIn();
        $.fn.leafletPXL._createCookie('leaflet_display', 'block' ,options.cookieActiveDays); 
    	} else {

       $('.leaflet').fadeOut();
       $.fn.leafletPXL._createCookie('leaflet_display', 'none' ,options.cookieActiveDays); 
    	}
       return false;
    });
}

//*** closes the leaflet */
$.fn.leafletPXL.__closeLeafletHandler=function()
{
    $('.leaflet_close').click(function()
    {   var options = $('.leaflet').data('leaflet_options');
    	$.fn.leafletPXL._createCookie('leaflet_xposition', $(".leaflet").css('left') ,options.cookieActiveDays);
    	$.fn.leafletPXL._createCookie('leaflet_yposition', $(".leaflet").css('top') ,options.cookieActiveDays);
      $.fn.leafletPXL._createCookie('leaflet_xdirection', options.xDirection ,options.cookieActiveDays);
      $.fn.leafletPXL._createCookie('leaflet_ydirection', options.yDirection ,options.cookieActiveDays);
      $.fn.leafletPXL._createCookie('leaflet_display', 'none' ,options.cookieActiveDays); 

			$('.leaflet').fadeOut();  	
       return false;
    });
}

$.fn.leafletPXL.__addItemToLeafletHandler=function()
{
    $('.leaflet_link').click(function()
    {
        $('.leaflet').fadeIn('slow',function()
	      { var options = $('.leaflet').data('leaflet_options');
	        $.fn.leafletPXL._createCookie('leaflet_display', 'block' ,options.cookieActiveDays); 
			$.fn.leafletPXL.addItem($('.leaflet_link'));				    
  	    });
		   	//entfernt auf wunsch: Merkzettel wird nach hinzufügen nicht mehr ausgeblendet.
		   	//setTimeout('$.fn.leafletPXL._closeMenu()',2500); 
    		return false;
    })
}

$.fn.leafletPXL.__printPDFHandler=function()
{
		$('.leaflet_printpdf').click(function()
		{
			leaflet_iframe_document.document.printpdf();
			return false;
		})
}

$.fn.leafletPXL.__sendemailHandler=function()
{
		$('.leaflet_email').click(function()
		{
			leaflet_iframe_document.document.sendemail();
			return false;
		})
}

})(jQuery);

document.leafletRefreshIntervalRun = 0;
document.leafletRefreshInterval;
document.curr_leaflet_items = 0;
document.validateCurrentLeaflet = function(newVal,oldVal)
{
	var oldVal = oldVal || document.curr_leaflet_items || 0;
	
	if(window.console){
		window.console.log('ov '+oldVal)
		window.console.log('nv '+newVal)
	
	};
	
	if(newVal-oldVal == 0)
	{
		if(window.console){window.console.log('killed')};
		clearInterval(document.leafletRefreshInterval);
		document.leafletRefreshIntervalRun = 0
	}
	
	if(document.leafletRefreshIntervalRun >= 10)
	{
		clearInterval(document.leafletRefreshInterval);	
		document.leafletRefreshIntervalRun = 0
	}
}
document.deleteItem = function()
{
			document.curr_leaflet_items--;
			clearInterval(document.leafletRefreshInterval)
			document.leafletRefreshIntervalRun = 0

			setTimeout(
			function()
			{
				var options = $('.leaflet').data('leaflet_options');
				var RANDOM = new Date().getTime()/1000;
				$('#leaflet_frame').attr('src',options.url+'?lang='+options.language+'&cache='+RANDOM).slideDown('fast');				
			},100);
						
			document.leafletRefreshInterval = setInterval(
			function()
			{
			if(window.console){window.console.log(document.leafletRefreshIntervalRun++)};
				var options = $('.leaflet').data('leaflet_options');
				var RANDOM = new Date().getTime()/1000;
				$('#leaflet_frame').attr('src',options.url+'?lang='+options.language+'&cache='+RANDOM).slideDown('fast');				
			
				if(document.leafletRefreshIntervalRun >= 10)
				{
					clearInterval(document.leafletRefreshInterval);
					document.leafletRefreshIntervalRun = 0
				} 

			},1000);
}