/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * jQuery Tour modified from codrops
 */
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;
    }
};

	$(function() {
		if ($.cookie('hidetours') != 'true'){
			//show the tour controls
			showControls();
			
			/*
			we can restart or stop the tour,
			and also navigate through the steps
			 */
			$('#activatetour').live('click',startTour);
			//$('#activatevideo').live('click',startVideo);
			$('#endtour').live('click',endTour);
			$('#restarttour').live('click',restartTour);
			$('#nextstep').live('click',nextStep);
		}	
		function startTour(){
			$('#activatetour').remove();
			$('#endtour,#restarttour').show();
			if(!autoplay && total_steps > 1)
				$('#nextstep').show();
			showOverlay();
			nextStep();
		}
		function startVideo(){
			var src = "accountexplanation.asp?whichacct=";
			$.fancybox({href:'http://www.youtube.com/v/S_XTVEhqJn0?fs=1&amp;hl=en_US',type:'swf'});
			overlayClose:true
		}
		function nextStep(){
			if(!autoplay){
				if(step == total_steps)
					step = 0;
				else
					$('#nextstep').show();
			}	
			if(step >= total_steps){
				//if last step then end tour
				endTour();
				return false;
			}
			++step;
			showTooltip();
		}
		
		function prevStep(){
			if(!autoplay){
				if(step > 2)
					$('#prevstep').show();
				else
					$('#prevstep').hide();
				if(step == total_steps)
					$('#nextstep').show();
			}		
			if(step <= 1)
				return false;
			--step;
			showTooltip();
		}
		
		function endTour(){
			step = 0;
			if(autoplay) clearTimeout(showtime);
			removeTooltip();
			hideControls();
			hideOverlay();
			var $confirmDiv = '<div id="dialog-confirm"><p>Hide other tours throughout the site?  This can be reset by clearing cookies, or visiting the Learning/Training page in the menu.</p></div>'
			$('BODY').prepend($confirmDiv);

			$( "#dialog-confirm" ).dialog({
						resizable: false,
						draggable: false,
						height:185,
						modal: true,
						buttons: {
							"Yes": function() {
								$( this ).dialog( "close" );
								document.cookie = "hidetours=true";
							},
							"No": function() {
								$( this ).dialog( "close" );
							}
						}
					});
		}
		
		function restartTour(){
			step = 0;
			if(autoplay) clearTimeout(showtime);
			nextStep();
		}
		
		function showTooltip(){
			//remove current tooltip
			removeTooltip();
			
			var step_config		= config[step-1];
			var $elem			= $('#' + step_config.name);
			
			if(autoplay)
				showtime	= setTimeout(nextStep,step_config.time);
			
			var bgcolor 		= step_config.bgcolor;
			var color	 		= step_config.color;
			
			var $tooltip		= $('<div id="tour_tooltip" class="tourTooltip" style="display:none;background-color:'+bgcolor+';color:'+color+'"><p>'+step_config.text+'</p><span class="tourTooltip_arrow"></span></div>');
			//position the tourTooltip correctly:
			
			//the css properties the tourTooltip should have
			var properties		= {'z-index' : 500};
			
			var tip_position 	= step_config.position;
			
			//append the tourTooltip but hide it
			$('BODY').prepend($tooltip);
			
			//get some info of the element
			var e_w				= $elem.outerWidth();
			var e_h				= $elem.outerHeight();
			var e_l				= $elem.offset().left;
			var e_t				= $elem.offset().top;
			switch(tip_position){
				case 'TL'	:
					properties = {
						'left'	: e_l,
						'top'	: e_t + e_h + 'px'
					};
					$tooltip.find('span.tooltip_arrow').addClass('tourTooltip_arrow_TL');
					break;
				case 'TR'	:
					properties = {
						'left'	: e_l + e_w - $tooltip.width() + 'px',
						'top'	: e_t + e_h + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_TR');
					break;
				case 'BL'	:
					properties = {
						'left'	: e_l + 'px',
						'top'	: e_t - $tooltip.height() + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_BL');
					break;
				case 'BR'	:
					properties = {
						'left'	: e_l + e_w - $tooltip.width() + 'px',
						'top'	: e_t - $tooltip.height() + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_BR');
					break;
				case 'LT'	:
					properties = {
						'left'	: e_l + e_w + 'px',
						'top'	: e_t + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_LT');
					break;
				case 'LB'	:
					properties = {
						'left'	: e_l + e_w + 'px',
						'top'	: e_t + e_h - $tooltip.height() + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_LB');
					break;
				case 'RT'	:
					properties = {
						'left'	: e_l - $tooltip.width() + 'px',
						'top'	: e_t + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_RT');
					break;
				case 'RB'	:
					properties = {
						'left'	: e_l - $tooltip.width() + 'px',
						'top'	: e_t + e_h - $tooltip.height() + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_RB');
					break;
				case 'T'	:
					properties = {
						'left'	: e_l + e_w/2 - $tooltip.width()/2 + 'px',
						'top'	: e_t + e_h + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_T');
					break;
				case 'R'	:
					properties = {
						'left'	: e_l - $tooltip.width() + 'px',
						'top'	: e_t + e_h/2 - $tooltip.height()/2 + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_R');
					break;
				case 'B'	:
					properties = {
						'left'	: (e_l + e_w/2 - $tooltip.width()/2) + 'px',
						'top'	: (e_t - $tooltip.height()-5) + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_B');
					break;
				case 'L'	:
					properties = {
						'left'	: e_l + e_w  + 'px',
						'top'	: e_t + e_h/2 - $tooltip.height()/2 + 'px'
					};
					$tooltip.find('span.tourTooltip_arrow').addClass('tourTooltip_arrow_L');
					break;
			}
			
			
			/*
			if the element is not in the viewport
			we scroll to it before displaying the tooltip
			 */
			var w_t	= $(window).scrollTop();
			var w_b = $(window).scrollTop() + $(window).height();
			//get the boundaries of the element + tooltip
			var b_t = parseFloat(properties.top,10);
			
			if(e_t < b_t)
				b_t = e_t;
			
			var b_b = parseFloat(properties.top,10) + $tooltip.height();
			if((e_t + e_h) > b_b)
				b_b = e_t + e_h;
				
			
			if((b_t < w_t || b_t > w_b) || (b_b < w_t || b_b > w_b)){
				$('html, body').stop()
				.animate({scrollTop: b_t}, 500, 'easeInOutExpo', function(){
					//need to reset the timeout because of the animation delay
					if(autoplay){
						clearTimeout(showtime);
						showtime = setTimeout(nextStep,step_config.time);
					}
					//show the new tooltip
					$tooltip.css(properties).show();
				});
			}
			else
			//show the new tooltip
				$tooltip.css(properties).show();
		}
	
		function removeTooltip(){
			$('#tour_tooltip').remove();
		}
		
		function showControls(){
			/*
			we can restart or stop the tour,
			and also navigate through the steps
			 */
			var $tourcontrols  = '<div id="tourcontrols" class="tourcontrols noprint">';
			$tourcontrols += '<span>Interactive Tour</span>';
			//$tourcontrols += '<span class="button" id="activatevideo">Video Introduction</span>';
			$tourcontrols += '<span class="button" id="activatetour">Start the tour</span>';
				if(!autoplay){
					$tourcontrols += '<div class="nav">';
					$tourcontrols += '<span class="button" id="nextstep" style="display:none;">Next ></span>';
				}
				$tourcontrols += '<span class="button" id="endtour">Close</span>';
			$tourcontrols += '</div>';
			
			$('BODY').prepend($tourcontrols);
			$('#tourcontrols').animate({'right':'30px'},500);
		}
		
		function hideControls(){
			$('#tourcontrols').remove();
		}
		
		function showOverlay(){
			var $overlay	= '<div id="tour_overlay"></div>';
			$('BODY').prepend($overlay);
		}
		
		function hideOverlay(){
			$('#tour_overlay').remove();
		}
	});

