jQuery.fn.simpleLightbox = function(_options){
	
	// defaults options
	var _options = jQuery.extend({
		lightboxContentBlock: '.lightbox',
		faderOpacity: 0.2,
		faderBackground: '#000000',
		closeLink:'a.close',
		href:true,
		onClick: null
	},_options);

	var _popupCounter = 1;

	return this.each(function(i, _this){
		var _this = jQuery(_this);
		if (!_options.href)
			_this.lightboxContentBlock = _options.lightboxContentBlock;
		else _this.lightboxContentBlock = _this.attr('href');
		if (_this.lightboxContentBlock != '' && _this.lightboxContentBlock.length > 1) {
			_this.faderOpacity = _options.faderOpacity;
			_this.faderBackground = _options.faderBackground;
			_this.closeLink = _options.closeLink;
			var _fader, _box = false;
			var _lightbox = $(_this.lightboxContentBlock);
			if (!jQuery('div.lightbox-fader').length)
				_fader = $('body').append('<div class="lightbox-fader"></div>');
			
			_fader = jQuery('div.lightbox-fader');
			_lightbox.css({
				'zIndex':999
			});
			_fader.css({
				opacity:_this.faderOpacity,
				backgroundColor:_this.faderBackground,
				display:'none',
				position:'absolute',
				top:0,
				left:0,
				zIndex:998,
				textIndent: -9999
			}).text('&nbsp;');
			_lightbox.shownFlag = false;
			_this.click(function(){
				if (jQuery.isFunction(_options.onClick)) {
					_options.onClick.apply(_this);
				}
				var _popupURL = 'postcard'+_this.attr('rel');
				var _rel  =  _this.attr('rel');
				
				if(jQuery('div[rel*="'+_popupURL+'"]').length == 0) {
					var _url = _this.attr('href');

					// get the html of the popup postcard
					//$.get('/assets/templates/dolceluna/markup/inc/lightbox.html', function(msg) {
					var patt=/postcards/;
					if (patt.test(window.location)) _url = '/assets/templates/dolceluna/inc/lightbox.html';
					$.get(_url, function(msg) {
						
						_lightbox = $(msg);
						_lightbox.attr('rel', _popupURL);
						_lightbox.css({
							zIndex:999,
							position:'absolute',
							display:'block',
							top: -9999,
							left: -9999
						});
						_lightbox.attr('id','ajaxpopup'+_popupCounter);
						jQuery('body').append(_lightbox);
						$('#ajaxpopup' + _popupCounter + ' img.image').attr('src', '/assets/images/postcards/' + _rel + '.jpg');
						$('#ajaxpopup' + _popupCounter + ' .button > input').attr('src', '/assets/templates/dolceluna/images/btn-send-popup.gif');
						
						_popupCounter++;
						
						// attach close event
						jQuery(_this.closeLink, _lightbox).click(function(){
							_lightbox.fadeOut(400, function(){
								_fader.fadeOut(300);
								_scroll = false;
								_this.attr('rel',_rel);
							});
							return false;
						});
						
						_this.send_btn = jQuery('.button input', _lightbox).not('.subscribe');
						_this.send_form = jQuery('.send-form', _lightbox);
						
						_this.fields = new Array('from-name', 'from-email', 'to-name', 'to-email');
						$('.send-form input[value*="..."]', _lightbox).focus(function (){
							for (var i = 0; i < _this.fields.length; i++) {
								var pat = /\.\.\./;
								if ($(this).val().match(pat)) {
									$(this).val('');
								}
							}
						});
				
						$('.send-form textarea', _lightbox).focus(function (){
							$('.send-form .alert-message', _lightbox).hide();
						});
				
						$('.send-form .alert-message', _lightbox).click(function (){
							$(this).hide();
							$('.send-form textarea', _lightbox).focus();
						});
				
						jQuery(_this.send_btn, _lightbox).click(function(){
							_senddata = _this.send_form.serialize();
							var inputs = new Array('from-name', 'from-email', 'to-name', 'to-email');
							$('input', _lightbox).each(function(index) {
								if (inputs[index]) _senddata += inputs[index] + '=' + $(this).val() + '&';
							});
							_senddata += "message=" + $('textarea', _lightbox).val() + "&";
							_senddata += "postcardid="+_rel;
							_senddata = _senddata.replace(/ /gi, '+');
							_sendurl = jQuery('.list-overview').attr('title');
							_sendurl = '/assets/templates/dolceluna/snippets/postcardsend.php';
							jQuery.ajax({
								url: _sendurl,
								global: false,
								type: "GET",
								dataType: "html",
								data: _senddata,
								success: function(msg){
									_box = $(msg).hide();
									$('body').append(_box);
									_box.css('zIndex',1001);
									_box.find('a.close').click(function(){
										_box.fadeOut(300, function(){
											_fader.fadeOut(300);
											_box.remove();
										});
									});
									_lightbox.fadeOut(300, function(){
										_box.fadeIn(300);
									});
									jQuery.fn.simpleLightbox.positionLightbox(_box);
								}
							});
							return false;
						});
				
						// show lightbox
						_lightbox.hide();
						_lightbox.shownFlag = true;
						jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
						_fader.fadeIn(300, function(){
							_lightbox.fadeIn(400);
							Cufon.refresh('.send-box .title');
							Cufon.refresh('.send-form label em');
							Cufon.refresh('.subscribe-fr strong');
							Cufon.refresh('.subscribe-fr .list li');
							Cufon.refresh('.subscribe-fr label');
							jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
						});
					});

/*
					$.ajax({
						url: _url,
						global: false,
						type: "GET",
						dataType: "html",
						data: "postcardid="+_rel,
            error: function(msg, ajaxOptions, thrownError){
							return false;
						},
						success: function(msg){
              _lightbox = $(msg);
							_lightbox.attr('rel', _popupURL);
							_lightbox.css({
								zIndex:999,
								position:'absolute',
								display:'block',
								top: -9999,
								left: -9999
							});
							_lightbox.attr('id','ajaxpopup'+_popupCounter);
							jQuery('body').append(_lightbox);
							_popupCounter++;
							
							// attach close event
							jQuery(_this.closeLink, _lightbox).click(function(){
								_lightbox.fadeOut(400, function(){
									_fader.fadeOut(300);
									_scroll = false;
									_this.attr('rel',_rel);
								});
								return false;
							});
							
							_this.send_btn = jQuery('.button input', _lightbox).not('.subscribe');
							_this.send_form = jQuery('.send-form', _lightbox);
							
							_this.fields = new Array('from-name', 'from-email', 'to-name', 'to-email');
							jQuery('.send-form input[value*="..."]', _lightbox).focus(function (){
								for (var i = 0; i < _this.fields.length; i++) {
									if (_this.fields[i] == $(this).attr('name')) {
										if (typeof(_this.fields[i]) != 'undefined') {
											jQuery(this).attr('value', '');
											delete _this.fields[i];
										}
									}
								}
							});
					
							jQuery('.send-form textarea', _lightbox).focus(function (){
								jQuery('.send-form .alert-message', _lightbox).hide();
							});
					
							jQuery('.send-form .alert-message', _lightbox).click(function (){
								jQuery(this).hide();
								jQuery('.send-form textarea', _lightbox).focus();
							});
					
							jQuery(_this.send_btn, _lightbox).click(function(){
								_senddata = _this.send_form.serialize();
								if (_senddata.length) _senddata +="&";
								_senddata += "postcardid="+_rel;
								_sendurl = jQuery('.list-overview').attr('title');
								jQuery.ajax({
									url: _sendurl,
									global: false,
									type: "GET",
									dataType: "html",
									data: _senddata,
									success: function(msg){
										_box = $(msg).hide();
										$('body').append(_box);
										_box.css('zIndex',1001);
										_box.find('a.close').click(function(){
											_box.fadeOut(300, function(){
												_fader.fadeOut(300);
												_box.remove();
											});
										});
										_lightbox.fadeOut(300, function(){
											_box.fadeIn(300);
										});
										jQuery.fn.simpleLightbox.positionLightbox(_box);
									}
								});
								return false;
							});
					
							// show lightbox
							_lightbox.hide();
							_lightbox.shownFlag = true;
							jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
							_fader.fadeIn(300, function(){
								_lightbox.fadeIn(400);
								Cufon.refresh('.send-box .title');
								Cufon.refresh('.send-form label em');
								Cufon.refresh('.subscribe-fr strong');
								Cufon.refresh('.subscribe-fr .list li');
								Cufon.refresh('.subscribe-fr label');
								jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
							});
						}
					});
*/
				} else {
					_fader.fadeIn(300, function(){
						_this.send_btn = jQuery('.button input',jQuery('div[rel*="'+_popupURL+'"]'));
						_this.send_btn.attr('rel',_rel);
						jQuery('div[rel*="'+_popupURL+'"]').fadeIn(400);
						jQuery.fn.simpleLightbox.positionLightbox(jQuery('div[rel*="'+_popupURL+'"]'));
					});
				}
				return false;
			});
			jQuery(_this.closeLink).click(function(){
				_lightbox.fadeOut(400, function(){
					_fader.fadeOut(300);
					_scroll = false;
				});
				return false;
			});
			_fader.click(function(){
				if (_box.length) _box.fadeOut(400);
				_lightbox.fadeOut(400, function(){
					_fader.fadeOut(300);
				});
				return false;
			});
			var _scroll = false;
			jQuery.fn.simpleLightbox.positionLightbox = function (_lbox) {
				var _height = 0;
				var _width = 0;
				var _minWidth = $('body > div').eq(0).outerWidth();
				if (window.innerHeight) {
					_height = window.innerHeight;
					_width = window.innerWidth;
				} else {
					_height = document.documentElement.clientHeight;
					_width = document.documentElement.clientWidth;
				}
				var _thisHeight = _lbox.outerHeight();
				var _page = $('body > div').eq(0);
				if (_lbox.length) {
					if (_width < _minWidth) {_fader.css('width',_minWidth);} else {_fader.css('width','100%');}
					if (_height > _page.innerHeight()) _fader.css('height',_height); else _fader.css('height',_page.innerHeight());
					if (_height > _thisHeight) {
						if ($.browser.msie && $.browser.version < 7) {
							_lbox.css({
								position:'absolute',
								top: (document.documentElement.scrollTop + (_height - _thisHeight) / 2)+"px"
							});
						} else {
							_lbox.css({
								position:'fixed',
								top: ((_height - _lbox.outerHeight()) / 2)+"px"
							});
						}
					}
					else {
						var _fh = parseInt(_fader.css('height'));
						if (!_scroll) {
						if (_fh - _thisHeight > parseInt($(document).scrollTop())) {
								_fh = parseInt($(document).scrollTop())
								_scroll = _fh;
							} else {
								_scroll = _fh - _thisHeight;
							}
						}
						_lbox.css({
							position:'absolute',
							top: _scroll
						});
					}
					if (_width > _lbox.outerWidth()) _lbox.css({left:((_width - _lbox.outerWidth()) / 2 + 10) + "px"});
					else _lbox.css({position:'absolute',left: 0});
				}
			}
			jQuery(window).resize(function(){
				if (_lightbox.is(':visible'))
					jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
			});
			jQuery(window).scroll(function(){
				if (_lightbox.is(':visible')) {
					jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
				}
			});
			jQuery.fn.simpleLightbox.positionLightbox(_lightbox);
				$(document).keypress(function (e){
				if (!e) evt = window.event;
				if (e.keyCode == 27) {
					if (_box.length) _box.fadeOut(400);
					_lightbox.fadeOut(400, function(){
						_fader.fadeOut(300);
					});
				}
			});
		}
	});
}

$(document).ready(function(){
	$('.open-lightbox').simpleLightbox({
		lightboxContentBlock: '.lightbox',
		faderOpacity: 0.1,
		faderBackground: '#000000',
		closeLink:'a.close',
		href:true,
		onClick: null
	});
});
$(window).bind('load', function(){
	if (!$.cookie('first-load')) {
		$('body > a.open-lightbox.hide').trigger('click');
		$.cookie('first-load','true');
	}	
});

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}

