// ---------------------------------------------------------------------
// [LIB] Login
// ---------------------------------------------------------------------

function login(showhide){
  if(showhide == "show"){
      document.getElementById('loginpopupbox').style.visibility="visible"; /* If the function is called with the variable 'show', show the login box */
  }else if(showhide == "hide"){
      document.getElementById('loginpopupbox').style.visibility="hidden"; /* If the function is called with the variable 'hide', hide the login box */
  }
}
  
// ---------------------------------------------------------------------
// [LIB] Carousel
// ---------------------------------------------------------------------

$(function() {
    var carousel   = $('#carousel_news');
    var news       = carousel.find('ul.news');
    var controls   = null; // Will hold the ul with the controls
    var timer      = null; // Will hold the timer div
    var wait       = 10000; // Milliseconds to wait for auto-switching
    var widths     = [];   // Will hold the widths of each image
    var items_size = news.find('li').length;
    var initialized = false;
 
    if (!items_size) { return; }
 
    // Controls html to append
    var controls_str = '<ul class="controls">';
    for ( var i = 1; i <= items_size; i++) {
       controls_str += '<li><a href="#">' + i + '</a></li>';
    }
    controls_str += '</ul>';
 
    // Cache the controls list
    controls = carousel.append(controls_str).find('ul.controls');
 
    // Make the first button in controls active
    controls.find('li:first a').addClass('active');
 
    // Hook to the controls' click events
    controls.find('li a').click(function(event) {
      move_news( $(this) );
      return false;
    });
 
    // Append the timer and cache it
    timer = carousel.append('<div class="timer"></div>').find('div.timer');
 
    // Store each item's width and calculate the total width
    news.find('li img')
        .each(function(i, e) {
            widths[i] = $(e).width();          
            if ( all_images_loaded() ) { init_carousel(); }
        })        
        .load(function(e) {
            var i = news.find('li img').index(this);
            widths[i] = $(this).width();
            if ( all_images_loaded() ) { init_carousel(); }
        });
 
 
    function all_images_loaded() {
      return (items_size == widths.length) && (jQuery.inArray(0, widths) < 0);
    }
 
 
    function move_news( new_active ) {
 
      // Move unless it is already moving
      if ( $('#carousel_news ul.news:animated').length > 1 ) {
        return false;
      }    
 
      var current_active = controls.find('li a.active');
 
      if (new_active == 'next') {
        var next = current_active.parent().next().find('a');
 
        if ( !next.length ) { next = controls.find('li:first a'); }
 
        new_active = next;
      }
 
      var current_index = parseInt(current_active.text(), 10) - 1;
      var new_index     = parseInt(new_active.text(), 10) - 1;
      var move_to       = new_index - current_index;
 
 
      if (!move_to) { return false; }
 
      var direction = (move_to > 0)? '-=': '+=';
 
      var move   = 0;
      var bottom = Math.min(current_index, new_index);
      var top    = Math.max(current_index, new_index);
 
      while (bottom < top) {
        move += widths[bottom];
        bottom++;
      }
 
      news.animate({marginLeft: direction + move }, 500);
      new_active.addClass('active');
      current_active.removeClass('active');
    }
 
    function animate_timer() {
      timer.stop().css({width: '100px'}).animate({width: '1px'}, wait);
    }
 
    // Initializer, called when all images are loaded
    function init_carousel() {
      if (initialized) { return false; }
 
      // Set the news ul total width
      var width = 0;
      for( var i = 0; i < widths.length; i++) { width += widths[i]; }
      news.width(width);
 
      // Make the news change every X seconds
      setInterval(function() { move_news('next'); animate_timer(); }, wait);
      animate_timer();
 
      initialized = true;
    }
});

// ---------------------------------------------------------------------
// [LIB] ImageScroller
// ---------------------------------------------------------------------

$(function() {

  //remove js-disabled class
	$("#viewer").removeClass("js-disabled");

  //create new container for images
	$("<div>").attr("id", "container").css({ position:"absolute"}).width($(".wrapper").length * 80).height(170).appendTo("div#viewer");
  	
	//add images to container
	$(".wrapper").each(function() {
		$(this).appendTo("div#container");
	});
	
	//work out duration of anim based on number of images (1 second for each image)
	var duration = $(".wrapper").length * 4000;
	
	//store speed for later (distance / time)
	var speed = (parseInt($("div#container").width()) + parseInt($("div#viewer").width())) / duration;
					
	//set direction
	var direction = "rtl";
	
	//set initial position and class based on direction
	(direction == "rtl") ? $("div#container").css("left", $("div#viewer").width()).addClass("rtl") : $("div#container").css("left", 0 - $("div#container").width()).addClass("ltr") ;
	
	//animator function
	var animator = function(el, time, dir) {
	 
		//which direction to scroll
		if(dir == "rtl") {
		  
		  //add direction class
			el.removeClass("ltr").addClass("rtl");
		 		
			//animate the el
			el.animate({ left:"-" + el.width() + "px" }, time, "linear", function() {
									
				//reset container position
				$(this).css({ left:$("div#imageScroller").width(), right:"" });
				
				//restart animation
				animator($(this), duration, "rtl");
				
				//hide controls if visible
				($("div#controls").length > 0) ? $("div#controls").slideUp("slow").remove() : null ;			
								
			});
		} else {
		
		  //add direction class
			el.removeClass("rtl").addClass("ltr");
		
			//animate the el
			el.animate({ left:$("div#viewer").width() + "px" }, time, "linear", function() {
									
				//reset container position
				$(this).css({ left:0 - $("div#container").width() });
				
				//restart animation
				animator($(this), duration, "ltr");
				
				//hide controls if visible
				($("div#controls").length > 0) ? $("div#controls").slideUp("slow").remove() : null ;			
			});
		}
	}
	
	//start anim
	animator($("div#container"), duration, direction);
	
	//pause on mouseover
	$("a.wrapper").live("mouseover", function() {
	  
		//stop anim
		$("div#container").stop(true);
		
		//show controls
		($("div#controls").length == 0) ? $("<div>").attr("id", "controls").appendTo("div#outerContainer").css({ opacity:0.7 }).slideDown("slow") : null ;
		($("a#rtl").length == 0) ? $("<a>").attr({ id:"rtl", href:"#", title:"rtl" }).appendTo("#controls") : null ;
		($("a#ltr").length == 0) ? $("<a>").attr({ id:"ltr", href:"#", title:"ltr" }).appendTo("#controls") : null ;
		
		//variable to hold trigger element
		var title = $(this).attr("title");
		
		//add p if doesn't exist, update it if it does
		($("p#title").length == 0) ? $("<p>").attr("id", "title").text(title).appendTo("div#controls") : $("p#title").text(title) ;
	});
	
	//restart on mouseout
	$("a.wrapper").live("mouseout", function(e) {
	  
		//hide controls if not hovering on them
		(e.relatedTarget == null) ? null : (e.relatedTarget.id != "controls") ? $("div#controls").slideUp("slow").remove() : null ;
		
		//work out total travel distance
		var totalDistance = parseInt($("div#container").width()) + parseInt($("div#viewer").width());
											
		//work out distance left to travel
		var distanceLeft = ($("div#container").hasClass("ltr")) ? totalDistance - (parseInt($("div#container").css("left")) + parseInt($("div#container").width())) : totalDistance - (parseInt($("div#viewer").width()) - (parseInt($("div#container").css("left")))) ;
		
		//new duration is distance left / speed)
		var newDuration = distanceLeft / speed;
	
		//restart anim
		animator($("div#container"), newDuration, $("div#container").attr("class"));

	});
									
	//handler for ltr button
	$("#ltr").live("click", function() {
	 					
		//stop anim
		$("div#container").stop(true);
	
		//swap class names
		$("div#container").removeClass("rtl").addClass("ltr");
							
		//work out total travel distance
		var totalDistance = parseInt($("div#container").width()) + parseInt($("div#viewer").width());
		
		//work out remaining distance
		var distanceLeft = totalDistance - (parseInt($("div#container").css("left")) + parseInt($("div#container").width()));
		
		//new duration is distance left / speed)
		var newDuration = distanceLeft / speed;
		
		//restart anim
		animator($("div#container"), newDuration, "ltr");
	});
	
	//handler for rtl button
	$("#rtl").live("click", function() {
							
		//stop anim
		$("div#container").stop(true);
		
		//swap class names
		$("div#container").removeClass("ltr").addClass("rtl");
		
		//work out total travel distance
		var totalDistance = parseInt($("div#container").width()) + parseInt($("div#viewer").width());

		//work out remaining distance
		var distanceLeft = totalDistance - (parseInt($("div#viewer").width()) - (parseInt($("div#container").css("left"))));
		
		//new duration is distance left / speed)
		var newDuration = distanceLeft / speed;
	
		//restart anim
		animator($("div#container"), newDuration, "rtl");
	});
});

// ---------------------------------------------------------------------
// [LIB] JQSlideMenu
// ---------------------------------------------------------------------

/*********************
//* jQuery Multi Level CSS Menu #2- By Dynamic Drive: http://www.dynamicdrive.com/
//* Last update: Nov 7th, 08': Limit # of queued animations to minmize animation stuttering
//* Menu avaiable at DD CSS Library: http://www.dynamicdrive.com/style/
*********************/

//Specify full URL to down and right arrow images (23 is padding-right to add to top level LIs with drop downs):
var arrowimages={down:['downarrowclass', '/lib/cssi/menu/down.gif', 23], right:['rightarrowclass', '/lib/cssi/menu/right.gif']}

var jqueryslidemenu={

animateduration: {over: 200, out: 100}, //duration of slide in/ out animation, in milliseconds

buildmenu:function(menuid, arrowsvar){
	jQuery(document).ready(function($){
		var $mainmenu=$("#"+menuid+">ul")
		var $headers=$mainmenu.find("ul").parent()
		$headers.each(function(i){
			var $curobj=$(this)
			var $subul=$(this).find('ul:eq(0)')
			this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
			this.istopheader=$curobj.parents("ul").length==1? true : false
			$subul.css({top:this.istopheader? this._dimensions.h+"px" : 0})
			$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: arrowsvar.down[2]} : {}).append(
				'<img src="'+ (this.istopheader? arrowsvar.down[1] : arrowsvar.right[1])
				+'" class="' + (this.istopheader? arrowsvar.down[0] : arrowsvar.right[0])
				+ '" style="border:0;" />'
			)
			$curobj.hover(
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					this._offsets={left:$(this).offset().left, top:$(this).offset().top}
					var menuleft=this.istopheader? 0 : this._dimensions.w
					menuleft=(this._offsets.left+menuleft+this._dimensions.subulw>$(window).width())? (this.istopheader? -this._dimensions.subulw+this._dimensions.w : -this._dimensions.w) : menuleft
					if ($targetul.queue().length<=1) //if 1 or less queued animations
						$targetul.css({left:menuleft+"px", width:this._dimensions.subulw+'px'}).slideDown(jqueryslidemenu.animateduration.over)
				},
				function(e){
					var $targetul=$(this).children("ul:eq(0)")
					$targetul.slideUp(jqueryslidemenu.animateduration.out)
				}
			) //end hover
		}) //end $headers.each()
		$mainmenu.find("ul").css({display:'none', visibility:'visible'})
	}) //end document.ready
}
}

//build menu with ID="myslidemenu" on page:
jqueryslidemenu.buildmenu("myslidemenu", arrowimages)

// ---------------------------------------------------------------------
// [LIB] Pageflip
// ---------------------------------------------------------------------

$(document).ready(function(){
	$("#pageflip").hover(function() {
		$("#pageflip img , .msg_block").stop()
			.animate({
				width: '307px', 
				height: '319px'
			}, 500); 
		} , function() {
		$("#pageflip img").stop() 
			.animate({
				width: '50px', 
				height: '52px'
			}, 220);
		$(".msg_block").stop() 
			.animate({
				width: '50px', 
				height: '50px'
			}, 200);
	});
});

// ---------------------------------------------------------------------
// [LIB] Bubble tip
// ---------------------------------------------------------------------

$(document).ready(function(){
	$("div.home_blog_popup ul li").hover(function() {
		$(this).find("div").stop()
		.animate({left: "120", opacity:1}, "fast")
		.css("display","block")

	}, function() {
		$(this).find("div").stop()
		.animate({left: "0", opacity: 0}, "fast")
	});
});

$(document).ready(function(){
	$("div.personals-popup ul li").hover(function() {
		$(this).find("div").stop()
		.animate({left: "60", opacity:1}, "fast")
		.css("display","block")

	}, function() {
		$(this).find("div").stop()
		.animate({left: "0", opacity: 0}, "fast")
	});
});

// ---------------------------------------------------------------------
// [LIB] Mini Calendar
// ---------------------------------------------------------------------

function buildCal(m, y, cM, cH, cDW, cD, brdr){
	var mn=['January','February','March','April','May','June','July','August','September','October','November','December'];
	var dim=[31,0,31,30,31,30,31,31,30,31,30,31];
	var oD = new Date(y, m-1, 1); //DD replaced line to fix date bug when current day is 31st
	oD.od=oD.getDay()+1; //DD replaced line to fix date bug when current day is 31st
	var todaydate=new Date() //DD added
	var scanfortoday=(y==todaydate.getFullYear() && m==todaydate.getMonth()+1)? todaydate.getDate() : 0 //DD added
	dim[1]=(((oD.getFullYear()%100!=0)&&(oD.getFullYear()%4==0))||(oD.getFullYear()%400==0))?29:28;
	var t='<div class="'+cM+'"><table class="'+cM+'" cols="7" cellpadding="0" border="'+brdr+'" cellspacing="0"><tr align="center">';
	t+='<td colspan="7" align="center" class="'+cH+'">'+mn[m-1]+' '+y+'</td></tr><tr align="center">';
	for(s=0;s<7;s++)t+='<td class="'+cDW+'">'+"SMTWTFS".substr(s,1)+'</td>';
	t+='</tr><tr align="center">';
		for(i=1;i<=42;i++){
			var x=((i-oD.od>=0)&&(i-oD.od<dim[m-1]))? i-oD.od+1 : 'X';
			var dD = x;
			if (x==scanfortoday) //DD added
			x='<span id="today">'+x+'</span>' //DD added
			if (x != 'X') {
				t+='<td class="'+cD+'"><a href="/calendar/today.cfm?date='+m+'-'+dD+'-'+y+'&daystoshow=7">'+x+'</a></td>';
			} else {
				t+='<td class="'+cD+'"></td>';
			}
			if(((i)%7==0)&&(i<36))t+='</tr><tr align="center">';
		}
	return t+='</tr><tr><td colspan="7" bgcolor="fbfbff"><div class="cslide_profile_buttons">&nbsp;&nbsp;<a href="/calendar/activity_add.cfm">Post an event</a> </div></td></tr></table></div>';
}



/*
 * JTip
 * By Cody Lindley (http://www.codylindley.com)
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 */

//on page load (as soon as its ready) call JT_init
$(document).ready(JT_init);

function JT_init(){
	   $("a.jTip")
	   .hover(function(){JT_show(this.href,this.id,this.name)},function(){$('#JT').remove()})
           .click(function(){return false});	   
}

function JT_show(url,linkId,title){
	if(title == false)title="&nbsp;";
	var de = document.documentElement;
	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var hasArea = w - getAbsoluteLeft(linkId);
	var clickElementy = getAbsoluteTop(linkId) - 3; //set y position
	
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseQuery( queryString );
	if(params['width'] === undefined){params['width'] = 250};
	if(params['link'] !== undefined){
	$('#' + linkId).bind('click',function(){window.location = params['link']});
	$('#' + linkId).css('cursor','pointer');
	}
	
	if(hasArea>((params['width']*1)+75)){
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_left'></div><div id='JT_close_left'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//right side
		var arrowOffset = getElementWidth(linkId) + 11;
		var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position
	}else{
		$("body").append("<div id='JT' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='JT_close_right'>"+title+"</div><div id='JT_copy'><div class='JT_loader'><div></div></div>");//left side
		var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); //set x position
	}
	
	$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});
	$('#JT').show();
	$('#JT_copy').load(url);

}

function getElementWidth(objectId) {
	x = document.getElementById(objectId);
	return x.offsetWidth;
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function parseQuery ( query ) {
   var Params = new Object ();
   if ( ! query ) return Params; // return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) continue;
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function blockEvents(evt) {
              if(evt.target){
              evt.preventDefault();
              }else{
              evt.returnValue = false;
              }
}

