// the global ready() block is at the end


 //found project to create php functions in js. www.phpjs.org
	//starting to play with it here by manually importing functions and attaching to $$ object

$$ = {
  basename : function(path, suffix) {
    var b = path.replace(/^.*[\/\\]/g, '');
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
      b = b.substr(0, b.length-suffix.length);
    }
    return b;
		}

} ;


/* MAPZ */
// really this should be in extend.js.jq, but until i get eri in-sync with that idea, it is stashed here in site-specific global
(function($){
  /*
    by default, if you pass coords mapz will skip geocoding.
    if you want to reverse-geocode, pass coords AND lookup:true.
    currently there is no logic for processing reverse-geocode results
    if there's a fulladdress and no marktitle, the former will be copied to the latter
    if there's a fulladdress and no coords, lookup will be set to true
  */

if ( $.gapiReady('maps') ) { //don't turn on mapz unless google api is already loaded.
  $.fn.mapz = function(options) {
    var opts = $.extend({}, $.fn.mapz.defaults, options) ;
    
    if (!opts.fulladdress && (!opts.coords.lat || !opts.coords.lon) ) {
      opts.coords = opts.defaultcoords ;
    }
    if (opts.fulladdress && (!opts.coords.lat || !opts.coords.lon) ) {
      opts.lookup = true ;
    }
    if (!opts.marktitle && opts.fulladdress) {
      opts.marktitle = opts.fulladdress ;
    }
    if (typeof options == "object"  && $.isProp(options.MTID)) opts.MTID = opts.MTID.toUpperCase() ;

    return this.each(function(){
      var oMap = {} ;
      oMap.opts = $.extend({}, opts) ;
      oMap.target  = this ;
      oMap.places = [] ;
      oMap.info    = new google.maps.InfoWindow({content:'hi!'}) ;
      oMap.addPlace = addPlace ;
      oMap.changePlace = changePlace ;
      
      oMap.places.push( {

        point     : new google.maps.LatLng(opts.coords.lat, opts.coords.lon) ,
        marker    : {} ,
        marktitle : opts.marktitle ,
        address   : opts.fulladdress
       }) ;
       
       oMap.place = oMap.places[oMap.places.length -1] ;
       if (opts.defaultmarker) {
         oMap.place.marker = new google.maps.Marker({position:oMap.place.point})
         if (oMap.place.marktitle) oMap.place.marker.setTitle(oMap.place.marktitle) ;
       }

      oMap.goptions = {
        center: oMap.place.point,
        zoom: opts.zoom,
        mapTypeId: google.maps.MapTypeId[opts.MTID]
      }
      
      oMap.canvas = new google.maps.Map(oMap.target,oMap.goptions) ;

      if (opts.defaultmarker) {
        oMap.place.marker.setMap(oMap.canvas);
        google.maps.event.addListener(oMap.place.marker, 'click', function() {
         oMap.info.open(oMap.canvas,oMap.place.marker);
        });
      }

      if (opts.lookup) {
        geocodeDefault(oMap) ;
      }
      
      var mml = $.fn.mapz.maps.push(oMap) ;
      
      if (opts.name) $.fn.mapz.maps[opts.name] = $.fn.mapz.maps[mml-1] ;
      if (this.id) $.fn.mapz.maps[this.id] = $.fn.mapz.maps[mml-1] ;

    });
  };
  
  $.fn.mapz.getMap = function(name) {
    if (!$.fn.mapz.maps.length) {
      return {} ;
    } else if (typeof name == 'undefined' || typeof name == 'null') {
      return $.fn.mapz.maps[0] ;
    } else if (name == 'latest') {
      return $.fn.mapz.maps[$.fn.mapz.length-1] ;
    } else if ( $.isProp($.fn.mapz.maps[name]) ) {
      return $.fn.mapz.maps[name] ;
    } else {
      return {} ;
    }
  };
  
  
  
  $.fn.mapz.defaults = {
    name: '' ,
    coords: {lat: 0 , lon: 0} ,
    lookup: false ,
    fulladdress: '' ,
    zoom: 13 ,
    MTID: 'ROADMAP' ,
    marktitle: '' ,
    defaultcoords: {lat: 37.871667 , lon: -122.2716667} ,
    defaultmarker: true
  };
  
  $.fn.mapz.maps = [] ;
  
  var geocoder = new google.maps.Geocoder() ;
  
  function geocodeDefault(mObj) {
    geocoder.geocode({address:mObj.opts.fulladdress}, function(data,status){ 
      if (status == google.maps.GeocoderStatus.OK){
        mObj.place.point = data[0].geometry.location ;
        mObj.place.marker.setPosition(mObj.place.point) ;
        mObj.canvas.setCenter(mObj.place.point) ;
      } else {
        mObj.canvas.setCenter(new google.maps.LatLng(mObj.opts.defaultcoords.lat, mObj.opts.defaultcoords.lng)) ;
      }
    });
  };
  
  function geocodePlace(place, map) {
    geocoder.geocode({address:place.address}, function(data,status){ 
      if (status == google.maps.GeocoderStatus.OK){
        place.point = data[0].geometry.location ;
        place.marker.setPosition(place.point) ;
        map.canvas.panTo(place.point) ;
      } else {
        place.pointStatus = status ;
      }
    });
  };

  function addPlace(options){
    var o = $.extend({coords: $.fn.mapz.defaults.defaultcoords, marktitle: '', address: '', wait:0}, options) ;
    var plc = this.places[this.places.push({})-1] ;
    plc.marker = new google.maps.Marker() ;
    plc.marker.setMap(this.canvas) ;
    plc.address = o.address ;
    plc.marktitle = o.marktitle ;
    if (plc.marktitle) plc.marker.setTitle(plc.marktitle) ;
    
    if (o.address) {
      if (o.wait) {
        var thismap = this ;
        setTimeout(function(){geocodePlace(plc, thismap)},o.wait) ;
      } else {
        geocodePlace(plc, this) ;
      }
    } else {
      plc.point = new google.maps.LatLng(o.coords.lat, o.coords.lon) ;
      plc.marker.setPosition(plc.point) ;
    }
  };
  
  function changePlace(options){
    // this = mapz map object
    var o = $.extend({coords: $.fn.mapz.defaults.defaultcoords, marktitle: '', address: ''}, options) ;
    this.place.address = o.address ;
    this.place.marktitle = o.marktitle ;
    if (this.place.marktitle) this.place.marker.setTitle(this.place.marktitle) ;
    
    if (o.address) {
      geocodePlace(this.place, this) ;
    } else {
      this.place.point = new google.maps.LatLng(o.coords.lat, o.coords.lon) ;
      this.place.marker.setPosition(this.place.point) ;
      this.canvas.panTo(this.place.point) ;
    }
  };
}		
})(jQuery);


/* IMAGECACHE */
// i think the imagecache is a good candidate for the general jquery extend file
(function($){
  $.imageCache = {} ;
  $.imageCache.cache = {} ;

  $.imageCache.load = function(oFileSet, options){
    var opts = jQuery.extend({}, jQuery.imageCache.load.defaults, options) ;

    for (var propname in oFileSet){
      $.imageCache.cache[propname] = {} ;
      $.imageCache.cache[propname].options = opts ;
      $.imageCache.cache[propname].type = opts.type ;
      $.imageCache.cache[propname].imgs = new Array() ;

      for (var i = 0; i < oFileSet[propname].length; i++) {
								if (opts.type == 'targeted') {
          $.imageCache.cache[propname].imgs[i] = {'oImg': new Image() , 'target': oFileSet[propname][i][0]} ;
          $.imageCache.cache[propname].imgs[i].oImg.src = oFileSet[propname][i][1] ;
								} else {
          $.imageCache.cache[propname].imgs[i] = new Image() ;
          $.imageCache.cache[propname].imgs[i].src = oFileSet[propname][i] ;
								}
      }

				  $(document).ready(function(){
						  $.imageCache.insert($.imageCache.cache[propname]) ;
						});
    }
  };

  $.imageCache.load.defaults = {
    type       : 'stacked' ,
    target     : 'div.slides' ,
    autocycle  : true ,
				curtain    : '' ,
    wrapclass  : 'image',
				stackclass : 'stack'
  };
		
		$.imageCache.insert = function(cache,options){
    var opts = jQuery.extend({}, cache.options, options) ;
    var imgs = cache.imgs ;
    var item = {} ;

    switch (opts.type) {
    		case 'stacked':
        for (var i = 0; i < imgs.length; i++) {
          item = $(document.createElement('div')).append(document.createElement('img')) ;
          $('img',item).attr('src',imgs[i].src) ;
          if (i > 0) $(item).addClass(opts.stackclass) ;
          $(opts.target).append( item ) ;
        }
								$(opts.target).cycle({pause:1,speed:4000,timeout:5000}) ;
								$(opts.target).cycle('pause') ;
        $(opts.target + ' div').removeClass(opts.stackclass) ;
								if ( opts.curtain ) {
								  var place = $(opts.target).offset() ;
										place.width = $(opts.target).css('width') ;
										place.height = $(opts.target).css('height') ;
          var $citem = $(document.createElement('div')).append($(document.createElement('img')).attr('src',opts.curtain)) ;
										$citem.addClass('curtain').css({left:place.left,top:place.top,width:place.width,height:place.height,position:'absolute','z-index':1000}) ;
          $('body').append( $citem ) ;
										$citem.fadeOut(5000,function(){
      				  if (opts.autocycle) $(opts.target).cycle('resume') ;
										  $citem.hide() ;
										}) ;
								} else {
    				  if (opts.autocycle) $(opts.target).cycle('resume') ;
								}
    				break;

    		case 'grouped':
        for (var i = 0; i < imgs.length; i++) {
          item = $(document.createElement('div')).append(document.createElement('img')) ;
          $('img',item).attr('src',imgs[i].src) ;
          $(opts.target).append( $(item).addClass(opts.wrapclass) ) ;
        }
								if ( $(opts.target).children(':last').css('float') != 'none' ) $(opts.target).append('<br class="clr" />') ;
								
    				break;

     	case 'targeted':
        for (var i = 0; i < imgs.length; i++) {
          item = document.createElement('img') ;
          $(item).attr('src',imgs[i].oImg.src) ;
          $('#' + imgs[i].target).append( item ) ;
        }
    				break;
    }
		};
})(jQuery);


jQuery.fn.piggybackLink = function(){
//this is how you trigger an anchor element from some other element's click
    return this.each(
      function(){
        $(this).click(function(event){
          location = $('a',this).attr('href') ;
          event.stopPropagation() ;
        });
      }
    );
};



/* PLUG-IN SUPPORT

/* add extra cycle transitions here */
if ( $.fn.cycle ) {
  $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
  	$cont.css('overflow','hidden');
  	opts.before.push($.fn.cycle.commonReset);
  	var h = $cont.height();
  	opts.cssBefore ={ top: h, left: 0 };
  	opts.cssFirst = { top: 0 };
  	opts.animIn	  = { top: 0 };
  	opts.animOut  = { top: -h };
  };
  $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
  	$cont.css('overflow','hidden');
  	opts.before.push($.fn.cycle.commonReset);
  	var h = $cont.height();
  	opts.cssFirst = { top: 0 };
  	opts.cssBefore= { top: -h, left: 0 };
  	opts.animIn	  = { top: 0 };
  	opts.animOut  = { top: h };
  };
  $.fn.cycle.transitions.scrollDownFade = function($cont, $slides, opts) {
  	$cont.css('overflow','hidden');
  	opts.before.push($.fn.cycle.commonReset);
  	var h = $cont.height();
  	opts.cssFirst = { top: 0 };
  	opts.cssBefore= { top: -h, left: 0 };
  	opts.animIn	  = { top: 0 };
  	opts.animOut  = { top: h , opacity:0.0 };
  };

}

/* JS & JQ GLOBAL BLOCKS -- NOT PLUG-INS */

// js implement of php global $template
// $$ is at the top of this file -- temp location!!

		$.Page = $$.basename(window.location.pathname,'.php') ;



/* SITE GLOBAL JQ READY BLOCK */

$(document).ready(function(){

		
   $('div.menu p').mousedown(function(){$(this).css('border-style','inset')}) ;
		 $('body.inner img.logoimg').setFakeLink('','','') ;

   $('div.tabs').initTabs() ;
		 if ($.cTabs[$.Page]) {
			  $('#' + $.cTabs[$.Page]).click() ;
		 }

		if ( $('div.header div').is('div.ticker') ) {
    $('div.ticker').cycle({cleartypeNoBg:true,fx:'scrollDownFade',pause:1,delay:-4500,speed:2500,timeout:6500,easeIn:'easeOutBounce'}) ;
		}
		
		$('div.facebox').draggable({axis:'y', handle:'div.boxctrl'}).click(function(){
		  $('div.facebox').toggleClass('hidden',1100) ;
		  $('div.facebox div.boxctrl').toggleClass('flag',1900) ;

				if ( $('div.facebox').hasClass('hidden') ) { // reversed from what you'd think due to jqui class-to-class animation processing time
				  $('div.facebox').attr('title',"click to close, drag by handle to move") ;
						$.cookie('fbox','open') ;
				  $.fbGroove() ;
				} else {
				  $('div.facebox').attr('title',"click to open, drag the handle to move") ;
						$.cookie('fbox','shut') ;
				}
		});
		
		$('div.facebox').hover(
		  function(){
				  $('div.facebox div.boxctrl').toggleClass('hover') ;
				}
		);

  if ( $.isEmptyObject($.cookie('fbox')) || $.cookie('fbox') == 'open' ) {
		  var df = setTimeout("$('div.facebox').click()", 1400) ;
		}

  $(document).scroll(function(){
		  $.fbGroove() ;
		/*  var fbo = $('div.facebox').offset() ;
				fbo.high = $('div.facebox').height() ;
				var fbx = {high: $('div.boxctrl').height()} ;
				fbo.bottom = fbo.top + fbo.high ;
				fbx.bottom = fbo.top + fbx.high ;
				var doctop = $(this).scrollTop() ;
				var vp = {high: $(window).height()} ;
				vp.bottom = vp.high + doctop ;
				fbo.clip = fbo.bottom - vp.bottom ;
				fbx.clip = fbx.bottom - vp.bottom ;
			
				if ( doctop > fbo.top ) {
				
				  $('div.facebox').animate({top: (doctop+32) + 'px'}) ;
						
				} else {
				
 				 if ( $.isEmptyObject($.cookie('fbox')) || $.cookie('fbox') == 'open') {
						
 					  if (fbo.clip > 0) {
   				   $('div.facebox').animate({top: (fbo.top-fbo.clip-36) + 'px'}) ; 
 							}
								
 				 } else {
						
 					  if (fbx.clip > 0) {
   				   $('div.facebox').animate({top: (fbo.top-fbx.clip-36) + 'px'}) ; 
 							}
								
 					}
					
				}	 */
  });
				
});

jQuery.fbGroove = function() {
		  var fbo = $('div.facebox').offset() ;
				fbo.high = $('div.facebox').height() ;
				fbo.bottom = fbo.top + fbo.high ;
				var fbx = {high: $('div.boxctrl').height()} ;
				fbx.bottom = fbo.top + fbx.high ;
				var doctop = $(document).scrollTop() ;
				var vp = {high: $(window).height()} ;
				vp.bottom = vp.high + doctop ;
				fbo.clip = fbo.bottom - vp.bottom ;
				fbx.clip = fbx.bottom - vp.bottom ;
			
				if ( doctop > fbo.top ) {
				
				  $('div.facebox').stop(true,true).animate({top: (doctop+32) + 'px'}) ;
						
				} else {
				
 				 if ( $.isEmptyObject($.cookie('fbox')) || $.cookie('fbox') == 'open') {
						
 					  if (fbo.clip > 0) {
   				   $('div.facebox').stop(true,true).animate({top: (fbo.top-fbo.clip-36) + 'px'}) ; 
 							}
								
 				 } else {
						
 					  if (fbx.clip > 0) {
   				   $('div.facebox').stop(true,true).animate({top: (fbo.top-fbx.clip-36) + 'px'}) ; 
 							}
								
 					}
					
				}	
};


