(function ($) {
    $.fn.marquee = function (klass) {
        var newMarquee = [],
            last = this.length;

        // works out the left or right hand reset position, based on scroll
        // behavior, current direction and new direction
        function getReset(newDir, marqueeRedux, marqueeState) {
            var behavior = marqueeState.behavior, width = marqueeState.width, dir = marqueeState.dir;
            var r = 0;
            if (behavior == 'alternate') {
                r = newDir == 1 ? marqueeRedux[marqueeState.widthAxis] - (width*2) : width;
            } else if (behavior == 'slide') {
                if (newDir == -1) {
                    r = dir == -1 ? marqueeRedux[marqueeState.widthAxis] : width;
                } else {
                    r = dir == -1 ? marqueeRedux[marqueeState.widthAxis] - (width*2) : 0;
                }
            } else {
                r = newDir == -1 ? marqueeRedux[marqueeState.widthAxis] : 0;
            }
            return r;
        }

        // single "thread" animation
        function animateMarquee() {
            var i = newMarquee.length,
                marqueeRedux = null,
                $marqueeRedux = null,
                marqueeState = {},
                newMarqueeList = [],
                hitedge = false;
                
            while (i--) {
                marqueeRedux = newMarquee[i];
                $marqueeRedux = $(marqueeRedux);
                marqueeState = $marqueeRedux.data('marqueeState');
                
                if ($marqueeRedux.data('paused') !== true) {
                    // TODO read scrollamount, dir, behavior, loops and last from data
                    marqueeRedux[marqueeState.axis] += (marqueeState.scrollamount * marqueeState.dir);

                    // only true if it's hit the end
                    hitedge = marqueeState.dir == -1 ? marqueeRedux[marqueeState.axis] <= getReset(marqueeState.dir * -1, marqueeRedux, marqueeState) : marqueeRedux[marqueeState.axis] >= getReset(marqueeState.dir * -1, marqueeRedux, marqueeState);
                    
                    if ((marqueeState.behavior == 'scroll' && marqueeState.last == marqueeRedux[marqueeState.axis]) || (marqueeState.behavior == 'alternate' && hitedge && marqueeState.last != -1) || (marqueeState.behavior == 'slide' && hitedge && marqueeState.last != -1)) {                        
                        if (marqueeState.behavior == 'alternate') {
                            marqueeState.dir *= -1; // flip
                        }
                        marqueeState.last = -1;

                        $marqueeRedux.trigger('stop');

                        marqueeState.loops--;
                        if (marqueeState.loops === 0) {
                            if (marqueeState.behavior != 'slide') {
                                marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir, marqueeRedux, marqueeState);
                            } else {
                                // corrects the position
                                marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir * -1, marqueeRedux, marqueeState);
                            }

                            $marqueeRedux.trigger('end');
                        } else {
                            // keep this marquee going
                            newMarqueeList.push(marqueeRedux);
                            $marqueeRedux.trigger('start');
                            marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir, marqueeRedux, marqueeState);
                        }
                    } else {
                        newMarqueeList.push(marqueeRedux);
                    }
                    marqueeState.last = marqueeRedux[marqueeState.axis];

                    // store updated state only if we ran an animation
                    $marqueeRedux.data('marqueeState', marqueeState);
                } else {
                    // even though it's paused, keep it in the list
                    newMarqueeList.push(marqueeRedux);                    
                }
            }

            newMarquee = newMarqueeList;
            
            if (newMarquee.length) {
                setTimeout(animateMarquee, 25);
            }            
        }
        
        // TODO consider whether using .html() in the wrapping process could lead to loosing predefined events...
        this.each(function (i) {
            var $marquee = $(this),
                width = $marquee.attr('width') || $marquee.width(),
                height = $marquee.attr('height') || $marquee.height(),
                $marqueeRedux = $marquee.after('<div ' + (klass ? 'class="' + klass + '" ' : '') + 'style="display: block-inline; width: ' + width + 'px; height: ' + height + 'px; overflow: hidden;"><div style="float: left; white-space: nowrap;">' + $marquee.html() + '</div></div>').next(),
                marqueeRedux = $marqueeRedux.get(0),
                hitedge = 0,
                direction = ($marquee.attr('direction') || 'left').toLowerCase(),
                marqueeState = {
                    dir : /down|right/.test(direction) ? -1 : 1,
                    axis : /left|right/.test(direction) ? 'scrollLeft' : 'scrollTop',
                    widthAxis : /left|right/.test(direction) ? 'scrollWidth' : 'scrollHeight',
                    last : -1,
                    loops : $marquee.attr('loop') || -1,
                    scrollamount : $marquee.attr('scrollamount') || this.scrollAmount || 2,
                    behavior : ($marquee.attr('behavior') || 'scroll').toLowerCase(),
                    width : /left|right/.test(direction) ? width : height
                };
            
            // corrects a bug in Firefox - the default loops for slide is -1
            if ($marquee.attr('loop') == -1 && marqueeState.behavior == 'slide') {
                marqueeState.loops = 1;
            }

            $marquee.remove();
            
            // add padding
            if (/left|right/.test(direction)) {
                $marqueeRedux.find('> div').css('padding', '0 ' + width + 'px');
            } else {
                $marqueeRedux.find('> div').css('padding', height + 'px 0');
            }
            
            // events
            $marqueeRedux.bind('stop', function () {
                $marqueeRedux.data('paused', true);
            }).bind('pause', function () {
                $marqueeRedux.data('paused', true);
            }).bind('start', function () {
                $marqueeRedux.data('paused', false);
            }).bind('unpause', function () {
                $marqueeRedux.data('paused', false);
            }).data('marqueeState', marqueeState); // finally: store the state
            
            // todo - rerender event allowing us to do an ajax hit and redraw the marquee

            newMarquee.push(marqueeRedux);

            marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir, marqueeRedux, marqueeState);
            $marqueeRedux.trigger('start');
            
            // on the very last marquee, trigger the animation
            if (i+1 == last) {
                animateMarquee();
            }
        });            

        return $(newMarquee);
    };
}(jQuery));

$().ready(function() {
	
	$('div#demo_marquee marquee').marquee('pointer').mouseover(function () {
            $(this).trigger('stop');
        }).mouseout(function () {
            $(this).trigger('start');
        }).mousemove(function (event) {
            if ($(this).data('drag') == true) {
                this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
            }
        }).mousedown(function (event) {
            $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
        }).mouseup(function () {
            $(this).data('drag', false);
        });
	
	if ($(".flash_info").length > 0 && $(".flash_info").text() != '') {
		$(".flash_info").fadeIn();
		var t=setTimeout("$('.flash_info').fadeOut('slow');",5000);
	}
	
	if (ghostShownCounted() < 2)
	{
		//showGhost();
	}
	
	var t;
	var indx = 0;

	function getImage(command) {
		var action = command;
		if (action != 'stop') {
			//$.get('getImage.php', { index: indx}, function(data){
				
				//$("div#imageContainer").replaceWith('<div id="imageContainer"><a href="monitoring" target="_blank"><img src="/media/img/kamera_imgs/' + indx + '.jpg" alt="" border="0" height="122" width="190"/></a></div>');
				
				//$("div#imageDemoContainer").replaceWith('<div id="imageDemoContainer"><a href="http://89.171.238.170:20000" target="_blank"><img src="/media/img/kamera_imgs/' + indx + '.jpg" alt="" border="0" height="375" width="500"/><br/><br/>Kliknij, aby uruchomić transmisję.</a></div>');
				
				if (indx < 16)
				{
					indx = indx + 1;
				}
				else
				{
					indx = 0;	
				}
		  //      if (data) {
					t = setTimeout(function(){getImage(action)},1000);
		  //      }
		  //  })
		}
	}
	function stop() {
		clearTimeout(t);
	}
	
	//getImage('start');
	timedCount();
});

function timedCount()
{
	var d = new Date();
	var t = d.getTime();
						
		
	//$('#reloader_cam').attr( 'src', 'http://85.89.172.31:880/snapshot.cgi?user=user&pwd=UseR321' );
	$('#reloader_cam').attr( 'src', 'http://85.89.172.31:880/snapshot.cgi?next_url=' + t + '&user=user&pwd=UseR321' );
	//alert('http://85.89.172.31:880//snapshot.cgi?next_url=' + t + '&user=user&pwd=UseR321');
	setTimeout('timedCount()',500);
}

function closeGhost()
{
	$("div#ghost").slideUp('fast', function(){ $(this).remove() });
	return false;
}
function showGhost()
{
	var a = $("<div>").attr('id', 'ghost').attr('class','ghost').hide();
 	$('body').append(a);
 	$('div#ghost').flash({
 		swf: '/media/img/popup_ndnd.swf',
 		width: 600,
 		height: 500,
 		wmode: 'transparent',
 		flashvars: {'clickTag':'/niania-dzis-na-dzis'},
 		params: {wmode: 'transparent'}
 	}); 
 	
 	var g_top = Math.ceil(($(window).height() - 500)/2);
 	var g_left = Math.ceil(($(document).width() - 600)/2);
	$("div#ghost").css("margin-top",g_top+"px").css("margin-left",g_left+"px").show();
	var s = ghostShownCounted();
		s++;
	var today = new Date();
		today.setTime( today.getTime() );
	var expires_date = new Date( today.getTime() + (1000 * 60 * 10) ); //10 min
	document.cookie = "ghost_shown="+s+"; expires="+expires_date.toUTCString();
	
	$(window).bind('scroll', function(){
	 	$(a).animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});
	});
	
}
function ghostShownCounted()
{
  if (document.cookie!="") {
  var toCookie=document.cookie.split("; ");
    for (i=0; i<toCookie.length; i++) { //4
      var nazwaCookie=toCookie[i].split("=")[0];
      var wartoscCookie=toCookie[i].split("=")[1]; 
      if (nazwaCookie=='ghost_shown') 
      	return unescape(wartoscCookie)
    }
  }
  return 0;
}
