if (!window.console) {
    window.console = {
        log: function () {},
        group: function () {},
        error: function () {},
        warn: function () {},
        groupEnd: function () {}
    };
}

jQuery.fn.offsetParents = function () {
	var temp_obj = new Object;
	temp_obj['top'] = 0;
	temp_obj['left'] = 0;
	if(jQuery(this).is('body'))
	{
		//do nothing
	}
	else
	{
		var recurse_obj = jQuery(this).offsetParent().offsetParents();
		temp_obj['top'] = jQuery(this).offsetParent().position().top + recurse_obj['top'];
		temp_obj['left'] = jQuery(this).offsetParent().position().left + recurse_obj['left'];
	}
	return temp_obj;
};
jQuery.fn.scrollTo = function (selector,callback){
	var animation = {scrollTop: $(selector).offset().top};
    $('html,body').animate(animation, 'slow', 'swing', function() {
        if (typeof callback == 'function') {
            callback();
        }
        callback = null;
    });
};
jQuery.fn.center = function (params) {
//	console.log("centering...");
	
	var defaults = {
		speed: 1000,
		onCenter: function(){},
		position: 'center',
		deadzone: 30//we don't want to have to center if the item is already within the acceptable limit
	};
	var p = $.extend(defaults,params);
	
    this.css("position","absolute");
    new_top_int = parseInt(( jQuery(window).height() - this.height() ) / 2+jQuery(window).scrollTop() - jQuery(this).offsetParents().top);
    new_left_int = parseInt(( jQuery(window).width() - this.width() ) / 2+jQuery(window).scrollLeft() - jQuery(this).offsetParents().left);
    new_top = new_top_int + 'px';
    new_left = new_left_int + 'px';
    
    old_top = jQuery(this).css('top');
    old_left = jQuery(this).css('left');
    old_top_int = parseInt(old_top.replace(/(.*?)px/,'$1'));
    old_left_int = parseInt(old_left.replace(/(.*?)px/,'$1'));
    
    switch (p.position) {
    case 'vcenter':
    	if(Math.abs(old_top_int - new_top_int) > p.deadzone)
		{
            jQuery(this).animate({
            	'top' : new_top
            },p.speed,p.onCenter);
		}
    	else
		{
    		p.onCenter.call();
		}
    	break;
    case 'hcenter':
    	if(Math.abs(old_left_int - new_left_int) > p.deadzone)
		{
            jQuery(this).animate({
            	'left' : new_left
            },p.speed,p.onCenter);
		}
    	else
		{
    		p.onCenter.call();
		}
    	break;
    case 'center':
	default:
    	if(Math.abs(old_left_int - new_left_int) > p.deadzone || Math.abs(old_top_int - new_top_int) > p.deadzone)
		{
            jQuery(this).animate({
            	'top'	: new_top,
            	'left'	: new_left
            },p.speed,p.onCenter);
		}
    	else
		{
    		p.onCenter.call();
		}
		break;
	}

    return this;
};
jQuery.fn.fadeToggle = function(speed, easing, callback) {
   return this.animate({opacity: 'toggle'}, speed, easing, callback);

};
/**
 * performs an Effect.BlindUp or Effect.BlindDown based on the 'display' style property of the element that is passed in
 * @param string obj_id (the id of the element you wish this effect to affect)
 */
function blind(obj_id,blind_id)
{
 jQuery("#" + obj_id).slideToggle("slow");
}
function fade_ul(ul_id,html) {
	Effect.tagifyText(ul_id);
    var listItems = jQuery(ul_id).select('li');
    var q = Effect.Queues.get('global');
    var obj = document.getElementById(ul_id);
    
    var effect = new Effect.multiple(listItems, Effect.Fade, {queue: {scope:'myscope', position:'end'},speed:0.01,afterFinishInternal:function(effect){effect.element.style.display = "block";},afterFinish:function(){obj.style.visibility = "hidden"; obj.innerHTML = html;}});
    q.add(effect);
    
}

function appear_ul(ul_id){
	Effect.tagifyText(ul_id);
	var listItems = jQuery(ul_id).select('li');
	for (index = 0, len = listItems.length; index < len; ++index)
	{
		listItems[index].style.display = "none";
	}
	
	var q = Effect.Queues.get('global');
	var obj = document.getElementById(ul_id);
	
	obj.style.visibility = "visible";
	
    var effect2 = new Effect.multiple(listItems, Effect.Appear, {queue: {scope:'myscope', position:'end'},speed:0.01,afterFinishInternal:function(){},afterFinish:function(){}});
    q.add(effect2);

}
function fall_ul(ul_id){
	Effect.tagifyText(ul_id);
	var listItems = jQuery(ul_id).select('li');
	new Effect.multiple(listItems, Effect.DropOut, {queue: 'end', speed:0.05, afterFinishInternal:function(){}});
}
function addRemoveClass(obj_id,classname)
{
	/*prototype method
//	var obj = document.getElementById(obj_id); 
	if(jQuery(obj_id).hasClassName(classname))
	{
		jQuery(obj_id).removeClassName(classname);
	}
	else
	{
		jQuery(obj_id).addClassName(classname);
	}*/
	/*jquery method*/
	jQuery("#" + obj_id).toggleClass(classname);
}
function addClassName(obj,classname)
{
	jQuery(obj).addClass(classname);//jquery specific
}
function removeClassName(obj,classname)
{
	jQuery(obj).removeClass(classname);//jquery specific
}
// Adds event to window.onload without overwriting currently 
// assigned onload functions.
function addLoadEvent(func,obj)
{
	if(obj == '')
	{
		obj = window;
	}
    var oldonload = window.onload;
    if (typeof window.onload != 'function')
    {
        obj.onload = func;
    } 
    else 
    {
        obj.onload = function()
        {
            oldonload();
            func();
        };
    }
}
/**
 * open_window only works with the windows plugin (not jquery compatible)
 */
function open_window(html,href,win_title,w,h,href_is_html,use_lightbox,show_ajax_loader)
{//FOR IE, ALWAYS DEFINE AT LEAST HEIGHT OR WIDTH
	var size = window.size();
	var effect = new PopupEffect(html, {className: "popup_effect2"});
	
	win = 
	new Window({maximizable: false, minimizable: false, recenterAuto: false, title: win_title, url: '', className: "alphacube",width: w,height: h, showEffect:effect.show.bind(effect), hideEffect:effect.hide.bind(effect)});
	win.setZIndex(150);


			
	if(size.width>=w && size.height>=h)
	{
		//win.setTitle(size.width + " x " + size.height);//debugging for IE
		win.showCenter(use_lightbox);
	}
	else
	{
		win.showCenter(use_lightbox,true);
	}

	
	if(href_is_html)
	{
		win.setHTMLContent(href);
	}	
	else
	{
		setTimeout(function(){win.setURL(href);},1000);
	}

  	myObserver = {
	  	/*onShow: function(eventName, thiswindow)
	  	{
		  	thiswindow.updateWidth();
			thiswindow.updateHeight();
	  	}*/
	  	
	  	onEndResize: function(eventName,thiswindow)
	  	{//just a handy debugger for the window
	  		thissize = thiswindow.getSize();
	  		thiswindow.setTitle(thissize.width + "x" + thissize.height);
	  	}
	};
	Windows.addObserver(myObserver);

	
  // 		{title: name, url: href, className: "alphacube",width: w,height: h, showEffect:effect.show.bind(effect), hideEffect:effect.hide.bind(effect)}
  	return false;		
}
function hideAndOpenLink(ref)
{
	var url = ref;
	win.hide();
	setTimeout(function(){window.location = url;},1250);
	
}
function hideAndRunScript(func)
{
	win.hide();
	setTimeout(function(){func();},1250);
}
//this makes the jquery overlay work in template 3,basic,basic2,explore
jQuery(function() { 

 	//PREVENT IE6 AND LOWER, AND OPERA FROM USING THE WINDOW. THEY WILL USE THE OVERLAY INSTEAD
 	//ALSO DECIDED THAT IE7 DOESN'T DO OFFSET CORRECTLY, SO I WILL ALSO DISABLE THIS FOR IE7
 	if(jQuery.browser.msie && jQuery.browser.version < 7 )
//	if(1==1)
 	{//#window doesn't work in IE6 and below, so replace them with #overlay
 		jQuery("a[rel='#window']").attr("rev",function(){
 			return jQuery(this).attr("rev").replace(/^.*?width=(\d+).*?$/,"$1");
 		});
 		jQuery("a[rel='#window']").each(function(){
 			jQuery(this).attr("rel","#overlay");
 		});
 	}
 	/** this section is for the programatic overlay loader
 	 * to use call openOveray() (note: does not work during the onload event)
 	 */
 	var api = jQuery("#overlay").overlay({api:true});//initialize the api
 	window.openOverlay = function(html,title,html_is_href,width,height){
 		api.onBeforeLoad(function(){
 			jQuery("#overlay").pngFix({include_self:true,ie7:true,ie8:true});
			var new_width = current_width = jQuery("#overlay").css("width").replace(/(\d+)px/,"$1");
	 		if(width)
	 		{
	 			var new_width = width;
	 		}
	 			
 			//set the new height based on the dimensions of the current backdrop image (keeping the aspect ratio currect)
 			//nh = old w * (image_ratio_height/imag_ratio_width)
 			
 			var new_height;
 			if(!height)
 			{
 				new_height = Math.round(new_width * (526/656));
 				
 			}
 			else
 			{
 				new_height = height;
 			}
			//console.log("new_height=["+new_height+"]");
			jQuery("#wrap").css("width",new_width + "px");
 			jQuery("#wrap").css("height",new_height + "px");			
 			this.resize(new_width + "px",new_height + "px");

 		});
 		api.onLoad(function(){
	 		var mytitle = '';
	 		var myhtml = html;
	 		var wrap = jQuery("#wrap");
	 		if(title)
	 		{
	 			mytitle = '<div class="overlay_title" style="width:'+(wrap.css("width").replace(/(\d+)px/,"$1") - 10)+'px">' + title + '</div>';
	 		}				
	 		if(html_is_href == true)
	 		{//if it's an http reference, then load it like it's ajax into an iframe
	 			myhtml = '<iframe id="wrapiframe" width="100%" height="'+(wrap.css("height").replace(/(\d+)px/,"$1") - 10)+'" frameBorder="0" allowtransparency="true"></iframe>';
	 			wrap.html(mytitle + myhtml);
	 			jQuery("#wrapiframe").attr('src','/fscode/javascript/jquery/overlay/loading.php?href=' + html.replace(/&/,"[amp]") + '&iframe=wrapiframe&height=' + (wrap.css("height").replace(/(\d+)px/,"$1"))/3);
	 		}
	 		else
	 		{
	 			wrap.html(mytitle + html);
	 		} 			
 		});
 		api.onClose(function(){
			var wrap = jQuery("#wrap");
			wrap.html("");//reset wrapper contents
			this.resetSize();//reset container size
 		});
 		api.load();//load the overlay
 	};
 	

 	/**
 	 * the following is code for all <a> links that have a ref of "#overlay"
 	 * you can define the width by using rev="[new width]" (ie rev="400")
 	 */
    // if the function argument is given to overlay, it is assumed to be the onBeforeLoad event listener 
    jQuery("a[rel='#overlay']").overlay(
    	{
    		
    		onBeforeLoad: function(){
    			
    			//makes the X in the corner "fade" appropriately in IE7 and IE8
    			jQuery("#overlay").pngFix({include_self:true,ie7:true,ie8:true});

    			var new_width = current_width = jQuery("div.overlay").css("width").replace(/(\d+)px/,"$1");
		 		if(this.getTrigger().attr("rev") != '')
		 		{
		 			var new_width = this.getTrigger().attr("rev").replace(/(\d+),\d+/,"$1");
		 		}
		 			
	 			//set the new height based on the dimensions of the current backdrop image (keeping the aspect ratio currect)
	 			//nh = old w * (image_ratio_height/imag_ratio_width)
	 			var new_height = Math.round(new_width * (526/656));
				
				//For IE6, these css settings must be set before calling resize()
				jQuery("div.wrap").css("width",new_width + "px");
	 			jQuery("div.wrap").css("height",new_height + "px");
	 			this.resize(new_width + "px",new_height + "px");
				
//	 			console.log(this);
	 		
    		},
    		onLoad: function() { 

	        // grab wrapper element inside content 
	        var wrap = this.getContent().find("div.wrap"); 
	 		var title = '';

	 		if(this.getTrigger().attr("title") != '')
	 		{
	 			title = '<div class="overlay_title" style="width:'+(wrap.css("width").replace(/(\d+)px/,"$1") - 10)+'px">' + this.getTrigger().attr("title") + '</div>';
	 		}				
			wrap.html(title + '<iframe id="wrapiframe" width="100%" height="'+(wrap.css("height").replace(/(\d+)px/,"$1") - 10)+'" frameBorder="0" allowtransparency="true"></iframe>');
			var new_href = this.getTrigger().attr("href").replace(/&/g,"[amp]");
			jQuery("#wrapiframe").attr('src','/fscode/javascript/jquery/overlay/loading.php?href=' + new_href + '&iframe=wrapiframe&height=' + (wrap.css("height").replace(/(\d+)px/,"$1"))/3);

			},
			onClose: function(){
				var wrap = this.getContent().find("div.wrap");
				wrap.html("");//reset wrapper contents
				this.resetSize();//reset container size
				if(this.getTrigger().attr("rev") != '')
				{
					jQuery("div.wrap").css("width",this.getOverlayWidth());
					jQuery("div.wrap").css("height",this.getOverlayHeight());
				}
			}
    });
    
//Moveable windows instead of overlay---------------------------------------------------------------------------------
    make_window = function(event){
    	event.preventDefault();//prevent default link behaviour so that we can instead open up a window
//    	console.log(event);
    	var options_temp = jQuery(this).attr("rev").split("&");
    	var options = new Object();
    	//default options
    	options["iframe"] = true;
    	options["overflow"] = true;
    	options["width"] = 640;
    	options["height"] = 480;
    	options["hpadding"] = 50;
    	options["vpadding"] = 60;
    	options["inlineHTML"] = "";//if empty, will use ajax to load the href link
//    	options["speed"] = 1000;//maybe later
    	options["buttons"] = "c";//options include: m,c,i
    	options["skin"] = "white";
    	options["position"] = "center";//options include center,none,vcenter,hcenter
    	
    	var aLink = this;
    	var window_id = "mainMBWindow";
    	var jq_win_id = "#" + window_id;

    	if(options_temp.length > 0)
    	{//convert options_temp into the "associative array" options 
	    	jQuery.each(options_temp,function(i){
	    		
	    		var option = this.split("=");
	    		options[option[0]] = option[1];//set the first section as the value
	    		
	    		//if there are any other values, concatinate them onto the end with an equals sign
	    		for(i=2;i<option.length;i++)
	    		{//need to do this for any items that have an equals sign in the value (i.e. html)
	    			options[option[0]] += "=" + option[i];//concatinate everything together
	    		}
	    	});
	    	if(options['id'])
	    	{
	    		window_id = options['id'];
	    		jq_win_id = "#" + window_id;
	    	}
    	}
    	if(jQuery(jq_win_id).length == 0)
    	{
    		//window object doesn't exist, so create it
    		var link_position = jQuery(aLink).position();
    		jQuery("#windows_container").append('<div id="'+ window_id +'" class="containerPlus draggable resizable" style=" top:'+ link_position.top +'px; left: '+ link_position.left +'px;"><div class="no"><div class="ne"><div class="n">'+ options['title'] +'</div></div><div class="o"><div class="e"><div class="c"><div class="mbcontainercontent"></div></div></div></div><div><div class="so"><div class="se"><div class="s"></div></div></div></div></div></div>');    		
    	}

			//set window object options
	    	jQuery.each(options,function(i){
	    		if(i)//sometimes i can be an empty string "" (this happens when no options are set with rev attribute)
	    		{
	    			jQuery(jq_win_id).attr(i,this);//i=>attrobute name, this=>attribute value
	    		}
	    	});			
    	jQuery(jq_win_id + " .mbcontainercontent").children().remove();//empty it out, if it already has items in it
		//create iframe string
    	if(options["overflow"] === true || options["overflow"] === "true")
    	{
    		scrolling = "auto";
    	}
    	else
		{
    		scrolling = "no";
		}
		var iframeHTML = "<iframe scrolling='"+scrolling+"' frameborder='0' allowtransparency='true' width='"+options['width']+"' height='"+options['height']+"' src='"+ jQuery(aLink).attr("href") +"'><p>Your browser does not support iframes.</p></iframe>";



    	//set window size
    	jQuery(jq_win_id).attr("width",0);
	    jQuery(jq_win_id).attr("height",0);
	    
    	//open window
    	if(!jQuery(jq_win_id).attr("inited"))
    	{
		    jQuery(jq_win_id).buildContainers({
		    	//unfortunately this code needs to change before uploading it to the server
		    	elementsPath:"/fscode/javascript/jquery/jquery.mbContainerPlus/elements/",
		    	onClose: function(){
		    		//when closing windows, destroy the contents (so that videos don't keep running in the bgrnd, etc.)
		    		jQuery(jq_win_id + " .mbcontainercontent").children().remove();
		    		jQuery(jq_win_id).attr("closed","false");//I'm never using mb_open, so why set closed to true?
		    	},
		    	onResize: function(){
		    	  var new_w = parseInt(jQuery(jq_win_id).css("width").replace(/(\d+)px/,"$1")) - options["hpadding"];
		    	  var new_h = parseInt(jQuery(jq_win_id).css("height").replace(/(\d+)px/,"$1")) - options["vpadding"];
		    	  jQuery(jq_win_id + " .mbcontainercontent > iframe").attr("width",new_w);
		    	  jQuery(jq_win_id + " .mbcontainercontent > iframe").attr("height",new_h);
		    	}
//				onCollapse:function(){console.log("onCollapse")},
//		        onIconize:function(){console.log("onIconize")},
////		        onClose: function(){},
////		        onResize: function(){},
//		        onDrag: function(){console.log("onDrag")},
//		        onRestore:function(){console.log("onRestore")}
		    });
    	}
    	else
		{
    		$(jq_win_id).find('.n').html(options['title']);
		}

		//window is initialized, so open it
		jQuery(jq_win_id).css({'display':'block'});
		jQuery(jq_win_id).css("width","0px");
		jQuery(jq_win_id).css("height","0px");
		
		//TODO: make the resizing optional after it's already been loaded
		jQuery(jq_win_id).mb_resizeTo(
			parseInt(options['height']) + options["vpadding"],
			parseInt(options['width']) + options["hpadding"],
			function(){
				load_content = function(){
					if(options["inlineHTML"] != "")
					{
						jQuery(jq_win_id + " .mbcontainercontent").html(options["inlineHTML"]);
					}
					else if(options["iframe"] == true)
					{
						jQuery(jq_win_id + " .mbcontainercontent").html(iframeHTML);
					}
					else
					{
			    		jQuery(jq_win_id + " .mbcontainercontent").load(jQuery(aLink).attr("href"));
					}					
				};
				if(options['position'] !== "none")
				{
					jQuery(this).center({'onCenter': load_content,'position': options['position']});
				}
				else
				{
					load_content();
				}
			}
		);
    	return false;
    };
    jQuery("a[rel='#window']").live('click',make_window);
	jQuery("[rel='#qtip']").each(function(){
		var container = undefined;
    	var options_temp = jQuery(this).attr("rev").split("&");
    	var options = new Object();
    	
    	//default options
    	options["container"] = "body";
    	options["use_container_parent"] = false;
    	
    	//combine default and passed options
    	consolidate_options(options,options_temp);
    	
		var content = new Object;
		if(options["content"])
		{
			content = {
				text: options["content"]
			};
			show = {when: {event: 'mouseover'}};
		}
		else if($(this).attr('title'))
		{
			content = {
				text: false
			};
			show = {when: {event: 'mouseover'}};
		}
		else
		{
			jQuery(this).click(function(event){
				event.preventDefault();//prevent default link behaviour so that we can instead open up a window
			});
			content = {
				url: this.href
			};
			show = {when: {event: 'click'}};
		}
		if(options["container"] === 'this')
		{
			options["container"] = this;
		}
		if(options["use_container_parent"])
		{
			container = $(options["container"]).parent();
		}
		else
		{
			container = $(options["container"]);
		}
		
		//merge metadata options with my default options (I may remove some of the code above as it is now redundent)
		var json_options = $.extend(true,{},{
			content: content,
			position: {
				corner: {
					target: 'rightMiddle',
					tooltip: 'bottomLeft'
				},
				container: container
			}
			,
			style: { 
				name: 'light',
				tip: 'bottomLeft',
				width: {max: 400},
				border: {
//					radius: 5,
					color: '#879EBC'
//					color: '#760F12'
				}
			},
			show: show,
			hide: {when: 'mouseout',fixed: true, delay: 100}
		},jQuery(this).metadata());//end default option merge
		
		//create tooltip
		jQuery(this).qtip(json_options);

	});
	jQuery('.define').each(function(){
		jQuery(this).css({'color':'#58792E','cursor':'help'});
		if(jQuery(this).attr('title'))
		{
			jQuery(this).qtip({
				style: 'green'
			});
		}
		else
		{
			jQuery(this).qtip({
				style: 'green',
				content: jQuery("#" + jQuery(this).html().toLowerCase().replace(/[^_a-zA-Z0-9-]/g,'_')).html()
			});
		}

	});
});
/**
 * used by jquery overlay loader to load the contents of the iframe (so that the "loading..." graphic will show
 */
function reload_child_iframe(iframe_id,href)
{
	jQuery('#'+iframe_id).attr('src',href.replace(/\[amp\]/g,"&"));
	//the replace() is for when I am sending a url that has &'s in it through GET 
	//if this is the case, use "[amp]" instead of "&" in your url when passing it over
}
function consolidate_options(options,options_temp)
{
	if(options_temp.length > 0)
	{//convert options_temp into the "associative array" options 
    	jQuery.each(options_temp,function(i){
    		
    		var option = this.split("=");
    		options[option[0]] = option[1];//set the first section as the value
    		
    		//if there are any other values, concatinate them onto the end with an equals sign
    		for(i=2;i<option.length;i++)
    		{//need to do this for any items that have an equals sign in the value (i.e. html)
    			options[option[0]] += "=" + option[i];//concatinate everything together
    		}
    	});
    	if(options['id'])
    	{
    		window_id = options['id'];
    		jq_win_id = "#" + window_id;
    	}
	}

}
