/**
 * 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)
{
/*scriptaculous/prototype way
//	if(typeof blind_id == 'undefined')
//	{
//		blind_id = obj_id;
//	}
	var obj = document.getElementById(obj_id);
	var effect;
//	var q = Effect.Queues.get('global');
	
	if(obj.style.display == 'none')
	{
		Effect.BlindDown(obj_id, {duration: 0.5, queue: {position: 'end', scope: obj_id}});
	}
	else
	{
		Effect.BlindUp(obj_id, {duration: 0.5, queue: {position: 'end', scope: obj_id}});
	}
*/
/*jquery way*/
 $("#" + obj_id).slideToggle("slow");
}
function fade_ul(ul_id,html) {
	Effect.tagifyText(ul_id);
    var listItems = $(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 = $(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 = $(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($(obj_id).hasClassName(classname))
	{
		$(obj_id).removeClassName(classname);
	}
	else
	{
		$(obj_id).addClassName(classname);
	}*/
	/*jquery method*/
	$("#" + obj_id).toggleClass(classname);
}
function addClassName(obj,classname)
{
	$(obj).addClass(classname);//jquery specific
}
function removeClassName(obj,classname)
{
	$(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
$(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 < 8 )
//	if(true)
 	{//#window doesn't work in IE6 and below, so replace them with #overlay
 		$("a[rel='#window']").attr("rev",function(arr){
// 			console.log("new rev=\"" + $(this).attr("rev").replace(/^.*?width=(\d+).*?$/,"$1") + "\"");
 			return $(this).attr("rev").replace(/^.*?width=(\d+).*?$/,"$1");
 		}).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 = $("#overlay").overlay({api:true});//initialize the api
 	window.openOverlay = function(html,title,html_is_href,width,height){
 		api.onBeforeLoad(function(){
 			//console.log('onBeforeLoad() is called...');
 			//console.log("width=[" + width + "]");
 			$("#overlay").pngFix({include_self:true,ie7:true,ie8:true});
			var new_width = current_width = $("#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+"]");
			$("#wrap").css("width",new_width + "px");
 			$("#wrap").css("height",new_height + "px");			
 			this.resize(new_width + "px",new_height + "px");

 		});
 		api.onLoad(function(){
	 		var mytitle = '';
	 		var myhtml = html;
	 		var wrap = $("#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>';
	 			//console.log("iframe height=["+(wrap.css("height").replace(/(\d+)px/,"$1"))+"]");
	 			wrap.html(mytitle + myhtml);
	 			$("#wrapiframe").attr('src','/fscode/javascript/jquery/overlay/loading.php?href=' + html.replace(/&/,"[amp]") + '&iframe=wrapiframe&height=' + (wrap.css("height").replace(/(\d+)px/,"$1"))/3);
//	 			$("#wrapiframe").attr('src',html);
	 		}
	 		else
	 		{
	 			wrap.html(mytitle + html);
	 		} 			
 		});
 		api.onClose(function(){
			var wrap = $("#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 
    $("a[rel='#overlay']").overlay(
    	{
    		
    		onBeforeLoad: function(){
    			
    			//makes the X in the corner "fade" appropriately in IE7 and IE8
    			$("#overlay").pngFix({include_self:true,ie7:true,ie8:true});
    			
   			
    			
//    			console.log($("img[overlay='true']"));
//    			console.log($("div.overlay").css("background-image"));
    			var new_width = current_width = $("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));
//				alert(new_width+"X"+new_height);
//				console.log("onBeforeLoad(resize"+new_width+"x"+new_height+")");
				
				//For IE6, these css settings must be set before calling resize()
				$("div.wrap").css("width",new_width + "px");
	 			$("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 = '';
//            $("img[overlay='true']").pngFix({include_self:true});//doesn't work! :[


	 		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>');
			$("#wrapiframe").attr('src','/fscode/javascript/jquery/overlay/loading.php?href=' + this.getTrigger().attr("href").replace(/&/,"[amp]") + '&iframe=wrapiframe&height=' + (wrap.css("height").replace(/(\d+)px/,"$1"))/3);
//			$("#wrapiframe").attr('src',this.getTrigger().attr("href"));

			},
			onClose: function(){
				var wrap = this.getContent().find("div.wrap");
				wrap.html("");//reset wrapper contents
				this.resetSize();//reset container size
				if(this.getTrigger().attr("rev") != '')
				{
					$("div.wrap").css("width",this.getOverlayWidth());
					$("div.wrap").css("height",this.getOverlayHeight());
				}
			}
    });
    
//Moveable windows instead of overlay---------------------------------------------------------------------------------
    $("a[rel='#window']").click(function(event){
    	event.preventDefault();//prevent default link behaviour so that we can instead open up a window
    	var options_temp = $(this).attr("rev").split("&");
    	var options = new Object();
    	//default options
    	options["iframe"] = true;
    	options["width"] = 640;
    	options["height"] = 480;
    	options["hpadding"] = 50;
    	options["vpadding"] = 60;
    	options["buttons"] = "c";//options include: m,c,i
    	options["skin"] = "white";
    	
    	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];
	    	});
	    	if(options['id'])
	    	{
	    		window_id = options['id'];
	    		jq_win_id = "#" + window_id;
	    	}
    	}
//    	console.log(options);
    	if($(jq_win_id).length == 0)
    	{
    		//window object doesn't exist, so create it
//    		console.log("//window object \"" + window_id +"\" doesn't exist, so create it");	    		
    		$("#windows_container").append('<div id="'+ window_id +'" class="containerPlus draggable resizable" style=" top:'+ aLink.offsetTop +'px; left: '+ aLink.offsetLeft +'px;"><div class="no"><div class="ne"><div class="n"></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>');
    		console.log(aLink.offsetTop,"aLink.offsetTop");
    	}
//		if(options_temp.length > 0 && options_temp[0] != "")//not needed now that I am setting some default options
//		{
			//set window object options
//			console.log("//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)
	    		{
	    			$(jq_win_id).attr(i,this);//i=>attrobute name, this=>attribute value
	    		}
	    	});			
//		}


		//create iframe string
		var iframeHTML = "<iframe frameborder='0' allowtransparency='true' width='"+options['width']+"' height='"+options['height']+"' src='"+ $(aLink).attr("href") +"'><p>Your browser does not support iframes.</p></iframe>";



    	//set window size
//    	console.log("//set window size");
//    	console.log($(jq_win_id).attr("width"));
    	$(jq_win_id).attr("width",parseInt(options['width']) + options["hpadding"]);
    	$(jq_win_id).attr("height",parseInt(options['height']) + options["vpadding"]);
//    	console.log($(jq_win_id).attr("width"));



    	//open window
    	if($(jq_win_id).attr("inited"))
    	{
    		//window is already initialized, so open it
    		if(options["iframe"] == true)
    		{
//    			console.log("set " + jq_win_id + " .mbcontainercontent to [" + iframeHTML + "]");
    			$(jq_win_id + " .mbcontainercontent").html(iframeHTML);
    			$(jq_win_id).mb_open();
    		}
    		else
    		{
//	    		console.log("//window is already initialized, so open it");
	    		$(jq_win_id).mb_open($(this).attr("href"));
    		}	
    	}
    	else
    	{
//    		console.log("//window is not initialized, so set content and run buildContainers()");
    		if(options["iframe"] == true)
    		{
    			$(jq_win_id + " .mbcontainercontent").html(iframeHTML);
    		}
    		else
    		{
    			$(jq_win_id).attr("content",$(this).attr("href"));
    		}
		    $(jq_win_id).buildContainers({
		    	//unfortunately this code needs to change before uploading it to the server
		    	elementsPath:"/explore/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.)
		    		$(jq_win_id + " .mbcontainercontent").children().remove();
		    	},
		    	onResize: function(){
//		    	  console.log($(jq_win_id).css("width") + " X " + $(jq_win_id).css("height"));
//		    	  console.log("resize iframe to match window size");
		    	  var new_w = parseInt($(jq_win_id).css("width").replace(/(\d+)px/,"$1")) - options["hpadding"];
		    	  var new_h = parseInt($(jq_win_id).css("height").replace(/(\d+)px/,"$1")) - options["vpadding"];
//		    	  console.log(new_w,"new_w");
//		    	  console.log(new_h,"new_h");
		    	  $(jq_win_id + " .mbcontainercontent iframe").attr("width",new_w);
		    	  $(jq_win_id + " .mbcontainercontent iframe").attr("height",new_h);
		    	}
		    });
    	}
    	return false;
    });

});
/**
 * 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\]/,"&"));
	//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
}