// JavaScript Document

// content ready
var contentReadyId = null;
var openHouseCookie = "aosaopenhouse";
// preload background
var img = new Image();
img.src = "styles/images/main_pagebg2.jpg";

var browser = 
   {
		 mozilla : false,
		 msie : false,
		 safari : false,
		 chrome : false,
		 version : 0
	}
	
var MAXDIR = 20;
var MINDIR = 5;
var STEP = 2;  // amount to move the glowers in one unit of time
var SPEED = 80;

var WaitingForContent = true;

function rnd ( num ) 
{
	 return Math.floor( Math.random() * num );
}

/*  Controlls a glower's matriculation
*/
function dirStat()
 {
	 this.dir = 0;      // - or + direction
	 this.count = 0;    // # of steps to take before chaning direction
	 var me = this;
	 this.init = function() 
	 {
		 me.count = MINDIR+rnd( MAXDIR-MINDIR )*(rnd(11) > 8 ? 1 : 0 );  // get a number between mindir & MAXDIR
		 me.dir = rnd( 2 ) ;   // flip a coin between - or +
		 
		 if ( me.dir < 1 )
		    me.dir = -1;
	 }
	 this.revdir = function() {  // to reverse the direction of the glower cuz we got to an edge
		 me.dir = -me.dir;
		 me.count = MINDIR;   // back off glower substantially
		 return (me.dir * STEP);
	 }
	 
	 // return the same direction from obtained during init until
	 // all requests for this direction have been exhausted then re-init
	 this.get = function() {
		 me.count--;
		 if ( me.count == 0 ) {
			 me.init();
		 }
		 //return ( dir  > 0 ) ? "+="+r+"px": "-="+r+"px";
		 return ( me.dir * STEP );
	 }
	 me.init();
 }


var xdir = new dirStat();
var ydir = new dirStat();
var XMIN = 0;
var XMAX = 0;
var YMIN = 0;
var YMAX = 0;

function moveglowers() {
	  try {
	      $(".glower").each(function() {
	          var pos = $(this).position();
	          //$(this).css( { left : xdir.get(), top : ydir.get() } );
	          var mypos = $(this).data("pos");
	          var newx = mypos.xdir.get();
	       
	          var newy = mypos.ydir.get();
	        
	          if (pos.left + newx < XMIN || pos.left + newx > XMAX) {
	              newx = mypos.xdir.revdir();
	          }
	        
	          if (pos.top + newy < YMIN || pos.top + newy > YMAX) {
	              newy = mypos.ydir.revdir();
	          }
	        
	          $(this).css({ left: (pos.left + newx) + "px", top: (pos.top + newy) + "px" });
	      });
	  }
	  catch ( e ) {
		 
	  }
}	

function glowers()
{	
   var glowContainer = $("#glowerpanel");
	
	var width = glowContainer.outerWidth();
	var height = glowContainer.outerHeight();
	
	$(".glower").each( function() { $(this).data("pos", { xdir : new dirStat(), ydir : new dirStat() } ) } );
	
	XMIN = 0;
	XMAX = width;
	YMIN = 0;
	YMAX = height;
	
   setInterval( moveglowers, SPEED );
}

function contentReady()
{ 
    clearTimeout( contentReadyId );
    WaitingForContent = false;	 
    var $content = $("#contentPage");
	 
	 function showPage() {
		 var animateOptions = { top : "0px" };
		 try {
			 if ( BrowserDetect.browser == "Firefox" ){
				 animateOptions =  { opacity : "1.0" };
				 $content.animate( animateOptions, "fast" );
			 }
			 else
				$content.css( { top : $content.parent().outerHeight()+"px" } )
						  .animate( animateOptions, "fast" )
						  .css( { position : "normal" } );
		 }
		 catch( e ) {
		 }
	 }
	 
    $("#pleasewaitpanel").fadeOut("fast", showPage);
}

function contentReadyCheck()
{
	if ( WaitingForContent == true ) {
		//alert("It appears you've been waiting a while for the page to appear!");
	}
}

function getContent( aref, pageTitle )
{
	 var url;
	 if ( typeof aref=="string") 
	    url = aref;
	 else {		 
	    url = aref.attr("href");		 
	 	 if ( url.indexOf("http:") != -1 ) {
       	 aref.attr("target", "_parent");
		    return true;
   	 }
		 if ( url.indexOf("#") == 0 ) {
			 return true;
		 }
		 if ( aref.attr("target") == "_new" ) {
			 return true;
		 }
	 }
	 
	 
	 // slide the page upward 
	 var $content = $("#contentPage");
	 
	 var animateOptions = {	top : "-"+$content.outerHeight()+"px" }
	 
	 // fire fox doesn't slide the div up properly
	 if ( BrowserDetect.browser == "Firefox" ){
		 animateOptions =  { opacity : "0" }
	 }
	 
	 $content.animate( animateOptions, "slow",
		  function() {			 
			 $("#pleasewaitpanel").fadeIn("fast", 
             function(){
					 WaitingForContent = true;
		 			 contentReadyId = setTimeout( contentReadyCheck, 2000 );
          	    $("iframe#content").attr({src: url});			 
				 });
		  } );
	 topicGuide.setTopic( aref, pageTitle );
	 return false;
}

function getTopicGuide()
{
	 var topic = $("#topicguide span");
	 var parent = $("#topicguide");
    var parentPos = parent.position();
    var pos = topic.position();
    var width =  parent.outerWidth();
	 var parentHeight = parent.outerHeight();
	 var height = topic.outerHeight();
	 var middleY = parentHeight / 2 - height/2;
    this.setTopic = function( aref, pageTitle ) {		    
			   topic.animate( { top : "130px" }, "fast", 
				function( ){ 
				   if ( typeof aref == "string" )
					   aref = "Welcome";
					var html = MainMenu.getMenuTopic( aref, pageTitle );
					if ( html == null )
					   html = aref.html();
				   $(this).html( html );
					var curwidth = $(this).outerWidth();
					$(this).css( { top : "0px", left : (width/2-curwidth/2)+"px" } );  
					// we're in relative mode so it's 0 from the parent position
					$(this).animate( { top : middleY+"px" }, "fast" );
				});
	 }
    	
}

function homePage()
{
	getContent( $("#home") );
}

function loadStartPage()
{
	 var loc = gup( "url" );
	 if ( loc ) {
		 var title = Url.decode( gup( "title") );
 	    getContent( loc, title );
	 }
	 else
	   getContent( $("#home") );
}

function adjustBrowserQuirks()
{
	if ( BrowserDetect.browser == "Explorer" ) {
		// goodSearch input is too low
		//var gs = $("#goodsearch_keywords_1");
		//gs.css( { top : (gs.position().top-8)+"px" } );
	}
}

/* Purpose is to make surea all references to any menu option are included here so that we can extrapolate the proper titles
   if links from an iframe are made to one the menu links
*/



var MainMenu = function MainMenuObj()
{
	  function MainMenuClass (){
		   var me = this;
			this.menulinks = new Array();
			this.getMenuTopic = function( ahrefOrUrl, pageTitle ) {
				  var url = ahrefOrUrl;
				  var title = "";
				  if ( typeof ahrefOrUrl != "string" ) {
					  url = ahrefOrUrl.attr("href");
					  title = ahrefOrUrl.attr("title");
				  }
				  if ( me.menulinks[ url ] )
				     return me.menulinks[ url ];				  
				  if ( typeof pageTitle == "string" && pageTitle.length > 0 )
				     return pageTitle;
              if ( title.length )
				     return title;					  
				  return null;
			}
		   this.init = function() {
				$("#mainmenu_text").accordion(
					  {   		 
						 active: true, 
						 alwaysOpen: true,
						 header: '.head', 		 
						 fillSpace: false,
						 event: "mouseover",
						 animation: "easeslide"
					  }
				  );
				//$("#mainmenu").after("<div id='papercurl'></div>");
				$("#mainmenu a").each(
      			 function() {
						  var url = $(this).attr("href");
						  var html = $(this).html();
						  if ( me.menulinks[ url ] == null )
						     me.menulinks[url] = html;
		   		 } );				
			}
         $onready.add( me.init );
	  }
	  return new MainMenuClass();
}();

var topicGuide = null;

function showNonProfitMsg()
{
	var $nfp = $("#nonprofit");
	$nfp.css( { left : "160px", top : "75px" } );
	$nfp.fadeIn( 200, function() { $nfp.fadeTo( 300, "0.58", 
											 function() { $nfp.fadeTo( 300, "1.0" ).css( { backgroundPosition : "0px -16px" } ); } ) } ); 
			 		  
}

var fadeOutId = "#logoTitle";
var fadeInId = "#logoTitle2";
var flipInterval = 500;
var flipSpeed = 3000;

function flipLogo()
{
	 $(fadeInId).fadeIn( flipSpeed );
  	 $(fadeOutId).fadeOut( flipSpeed );    
	 
	 // swap them for next time
	 var t = fadeInId;
	 fadeInId = fadeOutId;
	 fadeOutId = t;

}

function setupLogoFlip()
{
	if ( BrowserDetect.browser != "Firefox" )
	   return;
		
   var div = $("<div id='logoTitle2' class='logoTitle'>");   
	$("body").append( div );
	$("#logoTitle2").css( { display : "none", "background-image" : "url(styles/images/aosalogo2.png)" , "z-index" : 2   });
	setInterval( flipLogo, flipInterval );	
}

function doAnimations()
{
	setupLogoFlip();

	$("#logoTitle, #logoTitle2").animate({ left : "10px"}, "slow" );
   $("#logoText").animate({ left : "55px" }, "slow", 
				
			 function() {
				 $("#logoMotto").animate( { left : "105px", width : "358px" }, "slow", showNonProfitMsg );
			 }
	);	
		
	var $MainPanel = $("#mainpanel");
	var mainPos = $MainPanel.position();
	$MainPanel.css( "left", $(window).width()+"px").animate({ left : mainPos.left+"px"}, "slow" );
	
	var $MainMenu = $("#mainmenu");
	var menuPos = $MainMenu.position();
	$MainMenu.css( "top", $(window).height()+"px").animate( { top : menuPos.top + "px"}, "slow", function() { setupMenuYinYang() } );
}

var topPos;
var yinYangSizeY = 10;
function setupMenuYinYang()
{
	var elem = $($("#mainmenu_text li").get(0));
   var pofs = elem.offsetParent().position();
	var topPos = elem.position();
	topPos.left = topPos.left - pofs.left;
	topPos.top = topPos.top - pofs.top;

	var $yinYang = $("#yinyang");

	$("#mainmenu_text").mousemove( 
							 function(e)
							 {
								 $yinYang.animate( { top : (e.pageY-yinYangSizeY)+"px" }, 5);
							 } );

   $yinYang.css( { left : "15px", top : topPos.top +"px" } ).fadeIn("slow");
	
}

function dialogReady()
{
	$("div.modal").fadeIn( 200 );
	$("div.dialog").fadeIn( 200 );
}

function hideDialog()
{
	$("div.modal").fadeOut( 200 );
	$("div.dialog").fadeOut( 200 );
}

 
function loadDialogUrl( url )
{
	if ( typeof url == "string" )
   	$("iframe#dialog").attr({src: url});			
	else { 
	   var xmlText;
		xmlText = "<html><head></head><body style='background-color: transparent; color:white; padding-top: 25px'><h1>Aikido of San Antonio Events</h1>On {0} Aikido of San Antonio will have a {1}<br><br>{2}</body></html>".format( url.when, url.what, url.description );     
 
      var d = $("iframe#dialog");
		d = d[0];
		d = d.contentWindow.document.open("text/html","replace");
		d.write( xmlText );
		d.close();
	}
}

function imageCount( maximages, callback )
{
	 var me = this;
    this.counter = 0;
	 this.maxImages = maximages;
	 this.callback = callback;
	 
	 this.count = function() {	 
		 me.counter++;
		 if ( me.counter >= me.maxImages )
			 me.callback();
		 
    }
	 	 
}

function initDialog( url )
{
	   
		function continueInit()
		{
			$("body").prepend("<div class='modal'></div><div class='dialog'> \
							  <iframe id='dialog' allowtransparency='true' frameborder='0' src='' \
							  width='480px' height='590px' scrolling='no'></div>");
			bg = $("div.modal");
			bg.css( { display : "none", "background-color" : "#888888", 
					 "opacity" : "0.5",
					 position : "absolute", 
					 top : "0px", left : "0px", width : "100%", height : "100%", "z-index" : "500" } );
			$("div.dialog").css(  { "background" : "transparent url(styles/images/dialog_panel.png) top left no-repeat",
											"z-index" : "500"
										 } );
			$("div.dialog").append("<div class='button'></div>");
			$(".dialog .button").css( { position : "absolute", display : "block", width : "22px" , height : "22px", 
											    top : "2px", left : "458px", "z-index" : "500", "cursor" : "pointer",
											    "background-image" : "url(styles/images/dialog_close.png)" } )
			                    .click( hideDialog )
			                    .hover( function() { $(this).css("background-position", "0px -23px") }, 
											    function () {$(this).css("background-position", "0px 0px") } );
			$("iframe#dialog").load( dialogReady );
			loadDialogUrl( url );
		}
		
		// preload all images when images have loaded we'll continue with init
		var imageCounter = new imageCount( 2, continueInit );
		
	   var bgimage = new Image();
		bgimage.onload = imageCounter.count;
		var buttons = new Image();
		buttons.onload = imageCounter.count;
		bgimage.src = "styles/images/dialog_panel.png";
		buttons.src = "styles/images/dialog_close.png"; 
		 	
}

function showFrameDialog( urlOrObj )
{ 
	var bg = $("div.modal");
	if ( bg.length == 0 ) {
		initDialog( urlOrObj );
	}
	else
	   loadDialogUrl( urlOrObj );	 
}

function animateInCanvas( img, expandOnStart ) {
	  if ( img == null ) {
		  return;
	  }
	  var canvas = $("#ad").get(0);
	  var context = ( canvas.getContext ) ? canvas.getContext( '2d' ) : null;
	  if ( context == null ) {
		 // punt!
		 return;
	  }	 
	  	  
	  var asp = img.width/img.height;
	  var imageMarginY = 20;
	  
	  var closeButton = new Image();

     function drawCloseButton() 
	  {
		  if ( closeButton == null )
		     return;
		  context.drawImage( closeButton, img.width - closeButton.width, 0 , closeButton.width, closeButton.height );
	  }
	  
	  closeButton.onload = function() {
		   if ( ratio == 1.0 ) {
				drawCloseButton();
				closeButton = null;
			}
	  }
	  closeButton.src = "images/advertisement/closebutton.png";
	  
	  function draw( img, size, center ) {		  	
	      context.clearRect( 0, 0, img.width, img.height );
			var nw = (img.width * size );
			var nh = (img.height * size); 			
			var x = 0;
			var y = 0;
			if ( center ){
				x = (img.width - nw)/2;
				y = (img.height - nh)/2;
				y += imageMarginY; // shift the pic down a bit so we can put a close button up
			}
			if ( center == false ) {
				$("#ad").attr("width", nw).attr("height",nh);
			}
		   context.drawImage( img, x, y, nw, nh );			
			
	  }
	  
	  var cp = $("#contentDiv");
	  var pos = cp.position();
	  var width = cp.outerWidth();
	  var height = cp.outerHeight();	 
	  
	  var anid;
	  var minRatio = 0.5;
     var ratio = minRatio;  // 50 % of original 
	  var maxRatio = 1.0;
	  function animator( delta )
	  {
		  if ( anid == -1 ) {			  
			  return;
		  }
		  ratio += delta;
		  
		  if ( delta < 0 ) {
		     test = ( ratio <= minRatio );
			  final = minRatio;
			  center = false;
		  }
		  else {
		     test = ( ratio >= maxRatio ) 
			  final = maxRatio;
			  center = true;
		  }
		  if ( test ) {
			  ratio = final;
			  clearInterval( anid );	
			  anid = -1;
			  if ( final == minRatio ) {
				  // bind an event to re-expand
				  $("*").unbind( "click.ad" );
				  $("#ad").bind("click.ad", showAd );				  
			  }
			  else {
				  $("*").unbind("click.ad").bind( "click.ad", function() { hideAd(); } );
			     //$("#ad").unbind( "click.ad").click( hideAd );
				  //$("#ad").unbind("click.ad").bind("click.ad", hideAd );
			  }
		  }
		  draw( img, ratio, center );
		  if ( ratio == 1.0 ) 
   		  drawCloseButton();
	  }
	  
	  function collapser()
	  {
		  ratio = maxRatio;
		  if ( anid != -1 )
   		  clearInterval( anid );
 	     anid = setInterval( function() { animator( -0.05 ) }, 50 );
	  }
	  
	  function expander()
	  {
		  ratio = minRatio;
	 	  if ( anid != -1 )
           clearInterval( anid );
		  anid = setInterval( function() { animator( 0.05 ) } , 50 );
	  }
	  
	  function hideAd()
	  {
		   collapser();
			$("#ad").animate( { left : "25px", top : "610px" } );
	  }
	  
	  function showAd()
	  {
		  if ( expandOnStart ) {
			  $("#ad").unbind("click");
			  $("#ad").attr("width", img.width ).attr("height", img.height + imageMarginY );
			  expander();
			  $("#ad").animate( { left : ( pos.left + (width - img.width)/2 ) +"px",
										 top : ( pos.top + ( height - img.height) / 2 ) + "px" }, 200, "swing" );
		  }
		  else {
			   $("#ad").hide();
				draw( img, minRatio, false );
				$("#ad").fadeIn( 200 ).fadeOut( 200 ).fadeIn();
				expandOnStart = true;
				$("#ad").bind("click.ad", showAd );	
		  }
	  }
	  
	  
	  showAd();
	  createCookie( openHouseCookie, 1, 1 );
	  
}


function advertisementInit()
{
	 var href = window.location.href;
	 var expandOnStart = href.indexOf( "?" ) == -1; // only expand if there are no parameters in the url.
	 var img = new Image();
	 img.onload = function() {
		 var c = readCookie( openHouseCookie );
		 if ( c != null )
		    expandOnStart = false;
		 // adjust advertisement to fit over content page
		 animateInCanvas( img, expandOnStart );
	 };
	 img.src = "images/advertisement/ad.png";
}

function init() {
	
	
	adjustBrowserQuirks()
   
  var glowerstr = "<div class='glower' style='left:{0}px;top:{1}px'></div>";
	$("#glowerpanel").append( glowerstr.format( 50, 70 ) )
                  .append( glowerstr.format( 50, 70 ) )
                  .append( glowerstr.format( 80, 77 ) )
						.append( glowerstr.format( 50, 37 ) )
						.append( glowerstr.format( 20, 97 ) );
	glowers();
	
	$("#mission1").hover( function() { $(this).fadeOut(300); $("#mission2").fadeIn(500); }, function(){ }  );
	$("#mission2").hover( function() {}, function() { $("#mission2").fadeOut(300); $("#mission1").fadeIn(500) } );
	
	doAnimations();
	
	//newsPanelInit();
		
	$("#contentPage").append("<iframe id='content' allowtransparency='true' frameborder='0' src='' width='98%' height='100%' scrolling='no'>");	
	
	$("a").click( function() { return getContent($(this)) } );   
	
	
	topicGuide = new getTopicGuide();
			
	loadStartPage();
	
	advertisementInit();

}

var waitForReadyId;
function readyToShow()
{
	 clearTimeout( waitForReadyId );
	 //alert('all done!');
	 $("#loading").hide(); 
	 init();
}


function waitforImages()
{
	  var cssImages = 0;
	  var images = new Array();
	  var msg = "";
	  $("#loading").append("<span>Aikido of San Antonio<br>Please Wait, Loading Page . . .</span>");
	  var span = $("#loading span");
	  var h = span.outerHeight();    
	  var dh = $(document).height();
	  span.css( { top : ((dh - h )/2)+"px", left : 0+"px" } );
	  $("*").each( 
		  function(){
			   var bi = $(this).css("backgroundImage");
				if ( images[bi] == null ){
					cssImages++;	
				   var img=new Image();
	            img.onload=function() { 
					    cssImages--; 
						 if ( cssImages == 0 ) { readyToShow() } 
						 };
               img.onerror=function() { cssImages--; if ( cssImages == 0 ) { readyToShow() } };					
					if ( bi.indexOf( "url") != -1 ) {
						bi = bi.substr(4, bi.length - 5 );
					}
					
               img.src=bi;
   				images[bi] = img;														
				}				
     	  });

     /* work around for ie8 */
     waitForReadyId = setTimeout( readyToShow, 5000 );
	  
	  if ( cssImages <= 0 )
	     readyToShow();
	  //init();
	  	  
}

$onready.add( waitforImages );
