$(document).ready(function(){
	rxdInit();													// Initialize default function

	function periodical() {
		$('h1 em').effect('shake', { times:6, direction: "up" }, 500);
	}
	
/*
$(document).ready(function(){
  $('p:first')
    .effect('shake', {times:3}, 300)
    .effect('highlight', {}, 3000)
    .hide('explode', {}, 1000 );  
});


function periodical() {
	$('#ad img').effect('shake', { times:3, direction: "up" }, 200);
}
$(document).ready(function() {
	var shake = setInterval(periodical, 5000);
	
	$('#ad img').click(function() { // updated: on click clear
		clearInterval(shake);
		$(this).hide('explode', {}, 1000 );
	})	
});
*/
	var shake = setInterval(periodical, 100);
	
	
	// Prevent nav links
	$('nav a').click(function(e) {
		e.preventDefault();
		return false;
	});
	
	jumpScroll();
	
	function jumpScroll() {											// scrolling for # links
		$('nav a[href*=#]').click(function() {
			var duration = 1000;
			var easing = 'swing';
			var newHash = this.hash;
			var target = $(this.hash).offset().top;
			var oldLocation = window.location.href.replace(window.location.hash, '');
			var newLocation = this;
			
			// make sure it's the same location
			if(oldLocation+newHash==newLocation){
				// animate to target and set the hash to the window.location after the animation
				$('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
					// add new hash to the browser location
					window.location.href=newLocation;
				});
				return false;
			}
		});
	}

	setInterval(function(){
		var time = printTime(60);
		$('#clock').html(time);
	}, 50);

	$('#contact-dialog').click(function(e) {						// Hide contact dialog on 'click'
		$(this).animate({'opacity': 0}, 300);
	});
});

function rxdInit(){
	contactPaper();
	newsTicker();
	//updateClock();
	updateIndicator();
}

function printTime(secs) {											// Print current time 00:00:00
	var sep = ':'; 						//seperator character
	var hours,minutes,seconds,time;
	var now = new Date();
	hours = now.getHours();
	if (hours < 12) {
		meridiem = 'am';
	} else {
		meridiem = 'pm';
	}
	hours = hours % 12;
	if (hours==0) {
		hours = 12;
	} 
	time = hours
	minutes = now.getMinutes();
	if (minutes<10) {
		minutes = '0' + minutes;
	}
	time += sep + minutes;
	if (secs) {
		seconds = now.getSeconds();
		if (seconds<10) {
			seconds = '0' + seconds;
		}
		time += sep + seconds
	} 
	return time + ' ' + meridiem;
}

var contactPaper = function() {										// Show / Hide contact Paper
    var $this = $("#contact"),
            p = $this.css('top'),
            onHover = function() {
                $this.hover(function() {
                    $this.animate({ top: '-45px' }, {duration: 'slow', queue: false });
                }, function() {
                    $this.animate({top: p}, {duration: 'slow', queue: false });
                });
            };
    setTimeout(onHover, 4000);
    $this.click(function() {
        $this.toggleClass("show");
    });
    $('nav .contact').click(function() {
        $this.toggleClass("show");
    });
};

// News Ticker 
var newsTicker = function() {
	var closeBtn = $("<span>x</span>");
	$('.ticker-inner').append(closeBtn);
	$('#ticker span').click(function(){
		$(this).parents('#ticker').slideUp('fast');
		$(this).remove();
	});
	
	setTimeout(function(){
            $('#ticker').slideDown('fast');
            setTimeout(function() {
                $('#ticker p').fadeOut('fast');
                setTimeout(function() {
                    $('#ticker p').fadeIn('fast').text("Sorry, roxdedy.pl is still under development:)");
			}, 2500);
		}, 4500);
	}, 500);
}

// Update Clock
function updateClock() {
	setTimeout(function(){
		document.getElementById('clock').value = new Date();
	}, 1000);
}
		
function updateIndicator() {
	document.getElementById('indicator').textContext = navigator.onLine ? 'online' : 'offline';
}

// get random number
// var rand = Math.random().toString().substring(2,4);

// var roxdedy = {
//	pages: [],
//	init: function(){
//		$.each(this.pages, function(){
//			this.init && this.init();
//		});
//		if(this.pages.length){
//			this.pages[0].load();
//		}
//	},
//	addPage: function(page){
//		this.pages.push(page);
//	},
//	
//	loadPage: function(page, data){
//		page.load(data);
//	}
//};	

//var spots = {
//	init: function(){
//		// add handlers;
//		$("#spots li a").live("click", function(e){
//			e.preventDefault();
//			spot.load($(e.target).attr("data-id"));
//		});
//	},
//	load: function(){
//		showSpinner();
//		$.ajax({
//			url: "/spots/",
//			complete: function(){
//				hideSpinner();
//				transition("#spots", "fade");
//			}
//		});
//	}
//};

// var spot = {
// init: function() {
//		$("#spot-back").click(function(){
//			transition("#spots", "push", true);
//		})
//	},
//	load: function(id) {
//		$.ajax({
//		url: "/spot/" + id,
//			complete: function(){
//				// Set the header
//				$("#spot .page-header h1").text(id);
//				transition("#spot", "push");
//			}
//		});
//	}
// };

// $(document).trigger("page-change", {
//	$el: $("#spot"),
// 	name: "Spot " + id,
//	transition: "push"
// });

// $(document).bind("page-change", function(e, data){
//	transition(data.$el, data.transition);
// });

// $(document).bind("page-change", function(e, data){
// 	data.$el
// 	.find(".page-header")
//	.text(data.name);
// });

// $(document).ready(function() {
//	roxdedy.init();
// });

// roxdedy.addPage(spots);
// roxdedy.addPage(spot);
// roxdedy.addPage(welcome);

// Check WebSocket
// if (window.WebSocket) {
//	$('ul#support').append("<li>WebSockets is supported</li>");
// } else {
//	$('ul#support').append("<li>WebSockets is not supported</li>");
// }

//var hasMotion = window.DeviceMotionEvent;
//if(hasMotion) {
//	alert("We got one!");
//}

// if(navigator.geolocation) {
//	$('ul#support').append("<li>Geolocation is supported</li>");
// } else {
//	$('ul#support').append("<li>Geolocation is not supported</li>");
// }

//if (Modernizr.canvas) {
//	$('ul#support').append("<li>Canvas is supported</li>");
//} else {
//	$('ul#support').append("<li>Canvas is not supported</li>");
//}

//Check WebSocket
// if (window.WebSocket) {
//	$('ul#support').append("<li>WebSockets is supported</li>");
// } else {
//	$('ul#support').append("<li>WebSockets is not supported</li>");
// }


// Category Dropdowns
// function setup_category_change(){
// 	$('#category').change(update_work);
// }

// function update_work() {
//	var category = $('#category').attr('value');
//	//$('<h2></h2>').insertBefore('#work-url');
//	$.get('get_works.php?category=' + category, show_work);
// }

//function show_work(data) {
//	$('#work-url').html(data);
//}

//(function($){
//	// var messageCookie = document.cookie;
//	$("#dialog").css({
//		left: $(window).width() / 2 - $("#dialog").width() / 2,
//		top: $(window).height() / 2 - $("#dialog").height() / 2
//	}).show();
//	
//	// onClick hide dialog 
//	$("#dialog button").click(function(){
//		$("#dialog").fadeOut(500, function() {
//			$(this).remove();
//		});
//	});
// })(jQuery);

// Canvas drawing
// function draw() {
//	if(canvas) {
//		var canvas = document.getElementById("myCanvas");
//		var context = canvas.getContext("2d");
//		context.strokeStyle = "rgba(0, 0, 55, 1)";
//		context.fillStyle = "rgba(0, 0, 55, 0.5)";
//		context.fillRect(10,10,100,100);
//		context.strokeRect(15,15,100,100);
//	}
//}

//$(document).ready(function() {
		//$('#submit').bind('click', function(){
		//	var valName = $('#name').val();
		//	var valEmail = $('#email').val();
		//	var valPhone = $('#phone').val();
		//	var valMessage = $('#message').val();
		//	$.post("ajax/form.php", {
		//				name:valName,
		//				phone:valEmail,
		//				email:valPhone,
		//				message:valMessage
		//			}, function(data) {
		//			alert('Fail Submission');
		//		}
		//	);
		//	return false;
		//});
		
		//$('table tbody').each(function(){
		//	$(this).find('tr').not(':first').hide();
		//});
/*
		var window = $('#windowSlider dd.window');
		var windowHeight = window.height();
		var	windowUl = $('#windowSlider dd.window').find('ul');
		var	buttons = $('#windowSlider').find('dd.btn');
		var	defaultWindowHeight = 207;
		//windowUl.find('> li').css({ height : '207px'});
			$('ol li.last').hover(function(){
				$this = $(this);
				var h = $this.parents('li').height();
				window.delay(100).animate({ height : h }, 500);
			}, function(){
				window.animate({ height : defaultWindowHeight }, 500);
			});
		
			buttons.click(function(){
				var $this = $(this);
				var	currentLi = $(window).find('li.current');
				var	prevLi = $(window).find('li.current').prev().height();
				var	nextLi = $(window).find('li.current').next('li').height();
				var	h = currentLi.height();
				var m = parseFloat(windowUl.css('marginTop'), 10);
					
					if($this.hasClass('next')) {
						if(nextLi){
							windowUl.delay(80).animate({ 
								marginTop : m - h + 'px'
							}, 400);
							currentLi.removeClass().next('li').addClass('current');
						} else {
							$this.fadeTo('slow', 0.3);
							return;
						}
					}		
					
					if($this.hasClass('prev')) {
						if(prevLi){
							$this.fadeTo('slow', 0.3);
						}
						windowUl.delay(80).animate({ 
							marginTop : m + h + 'px'
						}, 500);
						currentLi.removeClass().prev('li').addClass('current');
					}
			});
	
    // alert("User appName is " + navigator.appName + "\nUser agent is " + navigator.userAgent);  
   
	
    // Change Logo on Hover
    //$('header h1 span').hover(function() {
    //   $(this).text('Edward Siwek');
    //}, function() {
    //    $(this).text('Roxdedy');
    //});

    // Show Resolution
    //$('#resolution').text($(window).width() + " : " + $(window).height());
    //$(window).resize(function() {
    //    $('#resolution').text($(window).width() + " : " + $(window).height());
    //});

    /* about-me */
    //setTimeout(function() {
    //	$("#content #about-me").show('slow');
    //}, 1400);

    //$(".about-me").click(function() {
    //    $("#about-me").show('slow');
    //    return false;
    //});
    //$("#close-me").click(function() {
    //    $("#about-me").hide('slow');
    //    return false;
    //});
//});


/*
//(function($){
	//count chars for textarea
	//var maxNum = 100;
	//$('#message').bind({
		//keypress : function() {
		//	var inputText = $(this).val();
		//	var lenghtChar = inputText.length;
		//	var charRemain = lenghtChar - maxNum;

		//	if (lenghtChar <= maxNum) {
		//	$('.counter').text(charRemain);
		//	} else if (lenghtChar > maxNum) {
		//	return false;
		//	}
		//}
	//});

	
	//create the loader
	var loader = $("<div></div>", {
				id: "loader"
		}).css("display", "block"),			
		bar = $("<span></span>").css("opacity", 0.2),		
		loadingInterval = null;
				
		//create bars
		for (var x = 0; x < 3; x++) {
			bar.clone().addClass("bar-" + x).appendTo(loader);
		}
				
				//add to page
				loader.insertAfter("#go");
				
				//animate
				function runLoader() {
					var firstBar = loader.children(":first"),
						secondBar = loader.children().eq(1),
						thirdBar = loader.children(":last");
						
					firstBar.fadeTo("fast", 1, function(){
						firstBar.fadeTo("fast", 0.2, function() {
							secondBar.fadeTo("fast", 1, function() {
								secondBar.fadeTo("fast", 0.2, function() {
									thirdBar.fadeTo("fast", 1, function() {
										thirdBar.fadeTo("fast", 0.2);
									});
								});
							});
						});
					});
				};
								
	//$("#go").toggle(function() {
	//		loader.show();
	//		loadingInterval = setInterval(function() { runLoader(); }, 1200);
	//}, function() {
	//	loader.hide();
	//	clearInterval(loadingInterval);
	//});
	
	// $("nav a").bind('click', function(e) {
	//	e.preventDefault();
	//	var nextPage = $(e.target.hash);
	//	$("#pages .current").removeClass("current");
	//	nextPage.addClass("current");
	//	$("nav").attr("className", e.target.hash.slice(1));
	// });
	
	
	//var visits = {
	//	history: [],
	//	add: function(page) {
	//		this.history.push(page);
	//	}
	// };
	
	// function loadPage(url, pageName) {
	// 	$("#" + pageName).load(url + " .wrapper", function(){
	// 		console.log(this);
	//		transition("#" + pageName, "fade", false);
	// 	});
	// };
	// loadPage("spots.html", "spots");
	
	//setup_category_change();
	
})(jQuery);
*/

// TESTING CODE

/*		
$(document).ready(function(){ 
	$(window).scroll(function() { 
		$('#contact').stop().animate({top: $(document).scrollTop()},'slow','easeOutBack'); 
	});
});	
*/

// lets get today date
//var now = new Date();
//hours = now.getHours();

// if(hours < 17) {
//	 $("#announcement").show();
//	 $('#page-overlay').show();
// }
//$("#announcement").click(function() {
//	$(this).hide('slow');
//	$('#page-overlay').hide();
//	return false;
//});

//$(document).ready(function(){
//        var message = "ROXDEDY";
//        var space="...";
//        var position=0;
//        function scroller(){
//            var newtext = message.substring(position,message.length) + space + message.substring(0,position);
//            var td = document.getElementById("tabledata");
//            td.firstChild.nodeValue = newtext;
//            position++;
//            if (position > message.length)
//            {
//                position = 0;
//            }
//            window.setTimeout(scroller,200);
//        }
// 
// 	Push and Pop
// The push() and pop() methods add or remove an element from the end of an array, respectively.
// Both methods modify the original array in place. The pop() method returns the element that has
// been removed (in our example, we use this to get the previous page), whereas the push() method
// returns the new length of the array.
//});
/*
<script type="text/javascript">
	$(document).ready(function() {
		var appCache = window.applicationCache;

		switch (appCache.status) {
		  case appCache.UNCACHED: // UNCACHED == 0
			return 'UNCACHED';
			break;
		  case appCache.IDLE: // IDLE == 1
			return 'IDLE';
			break;
		  case appCache.CHECKING: // CHECKING == 2
			return 'CHECKING';
			break;
		  case appCache.DOWNLOADING: // DOWNLOADING == 3
			return 'DOWNLOADING';
			break;
		  case appCache.UPDATEREADY:  // UPDATEREADY == 4
			return 'UPDATEREADY';
			break;
		  case appCache.OBSOLETE: // OBSOLETE == 5
			return 'OBSOLETE';
			break;
		  default:
			return 'UKNOWN CACHE STATUS';
			break;
		};
		
		appCache.update(); // Attempt to update the user's cache.
		if (appCache.status == window.applicationCache.UPDATEREADY) {
			appCache.swapCache();  // The fetch was successful, swap in the new cache.
		}
	});
</script>
  <!--
 /*
* This is a multi-line
* Comment
*/
/*
    var map;
    var geodan = new google.maps.LatLng(0,0);
    var osmMapType = new google.maps.ImageMapType({
	getTileUrl: function(coord, zoom) {
		return "http://tile.openstreetmap.org/" +
		zoom + "/" + coord.x + "/" + coord.y + ".png";
	},
	tileSize: new google.maps.Size(156, 156),
	isPng: true,
	alt: "OpenStreetMap layer",
	name: "OpenStreetMap",
	maxZoom: 19
});
 
function initialize() {
	var mapOptions = {
  	  	  zoom: 2,
  	  	  center: geodan,
  	  	  mapTypeId: 'OSM',
  	  	  mapTypeControlOptions: {
  	  	  	  mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP],
  	  	  	  style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
  	  	  }
  	};
	map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
	map.mapTypes.set('OSM',osmMapType);
	map.setMapTypeId('OSM');
}

    if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(pos) {
			var latitude = pos.coords.latitude;
			var longitude = pos.coords.longitude;

			var options = {position:new google.maps.LatLng(latitude, longitude),title:"Your location"};
				
			var marker = new google.maps.Marker(options);
			
			var circle = new google.maps.Circle({
				map:map, radius:pos.coords.accuracy
			});
			circle.bindTo('center', marker, 'position');
			
			marker.setMap(map);
			
			map.setCenter( new google.maps.LatLng(latitude, longitude));
		}, 
		function(error) {
			console.log(error.message);
		},{enableHighAccuracy:true});
	}
  </script>
  <script>
  var msg = window.webkitNotifications.createNotification('', 'Test Notification', 'Hello World');
  
  </script>
  */
  /*
  $(window).resize(function() {
    TT.setTips();
});

// 9NsjJ8nu.

function showIconOverlay(title, description) {
    $toolpit = $('<div class="tooltip-box"><h6>' + title + '</h6><p>' + description + '</p></div>').appendTo('body');
}

function registerNewBieHoverEvent() {
    // floating tooltip-box
    var positionTooltip = function(event) {
        var tPosX = event.pageX - 12;
        var tPosY = event.pageY + 10;
        $(".tooltip-box").css({ top: tPosY, left: tPosX });
    };

    $('.toolpit, .newbi-icon, .default-icon, .icon-uk, .worldwide-icon').hover(
        function(e) {
            $(".tooltip-box").fadeIn('fast');
        },
       function() {
           $('.tooltip-box').hide().remove();
       }
    ).mousemove(positionTooltip);
}

function bannerRotator() {
        var parent = $('ul.banners'),
            buttons = $('ul.buttons li'),
            current = parent.find('li.active'),
            currentIndex = current.index() + 1;

        current.fadeOut('400').removeClass('active');
        if ((currentIndex) % 5 == 0) {
            parent.find("li:first").fadeIn('600').addClass('active');
        } else {
            current.next('li').fadeIn('600').addClass('active');
        }
        t = setTimeout(bannerRotator, 4000);
}

    $(document).ready(function() {
        $("div.footer").find("a").click(function(e) {
            e.preventDefault();
        });

        // banners rotator for biddi home
        $('ul.buttons li').click(function(e) {
            var getButtonIndex = $(this).index() - 1,
                banners = $('ul.banners li'),
                activeBanner = banners.hasClass('active');

            banners.each(function(index) {
                if ($(this).hasClass("active")) {
                    $(this).removeClass('active').css("display", "none");
                };
            });
            clearTimeout(t);
            banners.eq(getButtonIndex).addClass('active');
            bannerRotator()
        });

        bannerRotator();

        $('table.invite-friends tr:even ').css({
            backgroundColor: "#f5f5f5"
        });

        // floating .fixed-side on window scroll
        var fs = "div.dont-miss-out";
        var checkVisible = $("div.whats-new").is("hidden");
        var fsY = null;
        var wrapperHeight = $('.wrapper').height();
        var fsHeight = $(fs).height();

        if ($(fs).css("top") != null) {
            if ($(fs).css("top").indexOf('px') >= 0)
                fsY = parseInt($(fs).css("top").substring(0, $(fs).css("top").indexOf("px")));
            else
                fsY = 0;
        }

        var floatTop = 0;
        if ($('.floating-inner').offset() != null) {
            floatTop = $('.floating-inner').offset().top;
        }

        var floatBottom = floatTop + fsHeight;

        $(window).scroll(function() {
            var sfMarker = fsY + $(document).scrollTop();
            if (sfMarker < floatTop) {
                $(fs).css({ position: "absolute", margin: "0 0 0 0" });
            }
            else {
                $(fs).css({ position: "fixed", margin: "-" + floatTop + "px 0 0 0" });
            }
        });

        $("div.content-inner").eq(1).prev("h2").css('margin-top', '-13px');
        $("div.content-inner").eq(2).prev("h2").css('margin-top', '-13px');
        $("div.content-inner").eq(3).prev("h2").css('margin-top', '-13px');
        $("div.content-inner").eq(4).prev("h2").css('margin-top', '-13px');

        $(".abidbuddyoverview").css('color', 'black');
        $(".abookbidbuddy").css("color", "#2d5578");
        $(".abookbidbuddy").click(
    function() {
        $(this).css("color", "#2d5578");
        $(".abidbuddyoverview").css('color', 'black')
        $('#BidBuddyPanel').show();
        $('#BidHistoryPanel').hide();
    });

        $(".abidbuddyoverview").click(function() {
            $(this).css("color", "#2d5578");
            $(".abookbidbuddy").css('color', 'black')
            $('#BidBuddyPanel').hide();
            $('#BidHistoryPanel').show();
        });

        $(".abiddinghistory").css("color", "#2d5578");
        $(".abiddinghistory").click(
    function() {
        $(this).css("color", "#2d5578");
        $(".amybids").css('color', 'black')
        $('#divBidhistory').show();
        $('#divMybids').hide();
    });

        $(".amybids").click(
     function() {
         $(this).css("color", "#2d5578");
         $(".abiddinghistory").css('color', 'black')
         $('#divBidhistory').hide();
         $('#divMybids').show();
     });

        $("div.recent-winner:first").addClass("first");
        $("div.recent-winner:last").addClass("last");

        $("div.section.ending ul.i210:last").css("border", "none");

        winnersTT('.winner-info', 'li');

    });


//function winnerHover(classItem, parentTag) {
//    var position= function(event) {
//        var PosX = event.pageX - 15;
//        var PosY = event.pageY + 30;
//        $(classItem).css({ top: PosY, left: PosX });
//    };

//    $(classItem).parent(parentTag).find("span").hover(function() {
//        var current = $(this).parent(parentTag);
//        cloneItem = current.find(classItem).clone();
//        
//        var offset = current.offset();
//        var parentTop = offset.top - 7;
//        var parentLeft = offset.left - 16;
//        var current = $(this).parent(parentTag);

//        cloneItem.appendTo('body').show();
//        $("<div class='stick-medal'></div>").css({ display: 'block', position: 'absolute', top: parentTop, left: parentLeft }).delay('400').show().appendTo("body");
//        $('.winner-medal:first').clone().appendTo(".stick-medal").css({ display: 'block' });
//        current.find('img').css("opacity", "1");
//    }, function() {
//        var current = $(this).parent(parentTag);
//        cloneItem.hide().remove();
//        $('.stick-medal').hide().remove();
//        current.find('img').css("opacity", "0.6");
//    }).mousemove(position);
//}
/*
function winnersTT(classItem, parentTag) {
    var contentTT = $('<div class="tt-content" />'),
        medal = $('<span class="medal" />'),
        overlay = $('<span class="overlay" />'),
        parentLi = $(classItem).parent(parentTag);
        positionTT = function(e) {
            var PosX = e.pageX - 10,
                PosY = e.pageY + 20;
            $(contentTT).css({ top: PosY, left: PosX });
        };

    var screenWidth = $(window).width();
    var screenBottom = $(window).scrollTop() + $(window).height();

    overlay.appendTo(parentLi).show();

    $(classItem).parent(parentTag).hoverIntent(function() {             // mouseOn
        var current = $(this),
            cloneInfo = current.find(classItem).clone();
            offset = current.offset();

        medal.appendTo(current).show();
        contentTT.appendTo("body").css({ display: 'block', position: 'absolute' });
        current.find('span.overlay').css('display', 'none');
        cloneInfo.appendTo(contentTT).show();

    }, function() {                                                     // mouseOut
        var current = $(this);
        medal.hide().remove();
        $(".tt-content").find(classItem).hide().remove().end().remove();
        current.find('span.overlay').css('display', 'block');
    }).mousemove(positionTT);
}

    var TT = {                                                          // tooltip rollhover for recent-winners
        delay: 600,
        setTips: function(){     
            $('img.winner-pic').css("opacity", "0.288");
            $('.tooltip').parent().hover(function(){
                // store the tooltip being hovered
                TT.current = $(this);
                TT.timer = setTimeout(function(){
                // find the tooltip, 
                TT.current.find("img.winner-pic").css("opacity", "1.0");
                TT.current.find(".tooltip").fadeIn('fast');
            }, TT.delay);
      }, function(){
            // on mouseout, clear timer and hide tooltip
            clearTimeout(TT.timer);
            TT.current.find("img.winner-pic").css("opacity", "0.288")
            $(this).find(".tooltip").fadeOut('fast');
      }).attr("title", ""); 										// clear the title to stop browser tooltips
    
    var screenWidth = $(window).width();
    var screenBottom = $(window).scrollTop() + $(window).height();
    
    $(".tooltip").each(function(){
      // grab the containing element
      $container = $(this).parent();
      
      // give it relative position if required
      if ($container.css("position") != 'absolute' 
          && $container.css("position") != "fixed") {
        $container.css({position: 'relative'});
      }
      
      var totalHeight = $container.height() + $(this).outerHeight();
      var width = $(this).outerWidth();
      var offset = $container.offset();
      
      // now we get the position the tip
      var top = $container.height(); // default placement
      var left = 0;
      
      // re-position if it's off the right of the screen
      if (offset.left + width > screenWidth) {
        left = 0 - width + 42;
        $(this).addClass('left');
      } else {
        $(this).removeClass('left');
      }
      
      // re-position if it's off the bottom of the screen
      if (offset.top + totalHeight > screenBottom) {
        top = 0 - $(this).outerHeight();
        $(this).addClass('above');
      } else {
        $(this).removeClass('above');
      }
      
      // finally set the css properties to position onscreen
      $(this).css({
        "top": top,
        "left": left
      });
    });
  }
}
*/
