/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

/*--------------------------------------------------------------------------*/ 
// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);

/*--------------------------------------------------------------------------*/ 

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

/*--------------------------------------------------------------------------*/

var Toggler = function (trigger, content) {
	this.trigger = $(trigger);
	this.content = $(content);
	this.setup();	
};
Toggler.prototype = {
	setup: function () {
		var self = this;
		this.trigger.toggle(
			function (ev) {
				ev.preventDefault();
				self.content.slideDown(300);
			},
			function (ev) {
				ev.preventDefault();
				self.content.slideUp(300);
			}
		);
	}
};

/*--------------------------------------------------------------------------*/

var YouTubePopUp = function(trigger, pop, width, height){
    this.trigger = $(trigger);
    this.pop = $(pop);
	this.container = this.pop.find('.content');
    this.width = width;
    this.height = height;
    this.matches = this.trigger.attr('href').match(/v=([A-Za-z0-9\-=_]{11})/);
    this.setup();
};
YouTubePopUp.prototype = {
    setup: function() {
        var self = this;
        this.trigger.bind('click', function (ev) {
            ev.preventDefault();
            self.open();
        });
    },
	open: function () {
		var self = this;
		if ($('#modal_overlay')) {
			this.init_modal($('#modal_overlay'));
		}
		this.pop.addClass('video');
		this.pop.css("width", this.width + 50);
		this.pop.css("height", this.height + 50);
		this.pop.center();
		this.pop.fadeIn(100, function () {
			self.embed_video();
		});
		
		var close_btn = this.pop.find('.close');
		close_btn.bind('click', function () {
			self.close();
		});
	},
	close: function () {
		var self = this;
		this.pop.fadeOut(100, function () {
			self.container.html('');
		});
		if ($('#modal_overlay')) {
			$('#modal_overlay').hide();
		}
	},
	init_modal: function (el) {
		el.css("height", $('body:first').height());
		$(el).show();
	},
    embed_video: function () {
        var url = "http://www.youtube.com/v/" + this.matches[1] + "&hl=en&autoplay=0";
		
        this.container.flash({
            swf: url,
            width: this.width,
            height: this.height
        });
    }
};

/****/
var ImagePopUp = function(trigger, pop, width, height){
    this.trigger = $(trigger);
    this.pop = $(pop);
	this.container = this.pop.find('.content');
    this.image = this.trigger.attr('href');
    this.width = width;
    this.height = height;
    this.setup();
};
ImagePopUp.prototype = {
    setup: function() {
        var self = this;
        this.trigger.bind('click', function (ev) {
            ev.preventDefault();
            self.open();
        });
    },
	open: function () {
		var self = this;
		if ($('#modal_overlay')) {
			this.init_modal($('#modal_overlay'));
		}
		this.pop.addClass('photo');
		this.pop.css("width", this.width + 50);
		this.pop.css("height", this.height + 50);
		this.pop.center();
		this.pop.fadeIn(100, function () {
			self.embed_photo();
		});
		
		var close_btn = this.pop.find('.close');
		close_btn.bind('click', function () {
			self.close();
		});
	},
	close: function () {
		var self = this;
		this.pop.fadeOut(100, function () {
			self.container.html('');
		});
		if ($('#modal_overlay')) {
			$('#modal_overlay').hide();
		}
	},
	init_modal: function (el) {
		el.css("height", $('body:first').height());
		$(el).show();
	},

        embed_photo: function (){
                var dsPhoto = $('<img />').attr('src', this.image);
                this.container.width = dsPhoto.width + 50;
                this.container.height = dsPhoto.height + 50;
                //dsPhoto.attr('width',this.width);
                //dsPhoto.attr('height', this.height);
	        this.container.append(dsPhoto);
        }
};

/*--------------------------------------------------------------------------*/

$(document).ready(function () {
	if ($.browser.msie && $.browser.version=="6.0") {
		try {
			document.execCommand('BackgroundImageCache', false, true);
		} catch (e) {}
	}
	
        //if ($('#media').length) {
                //$('#media .video a').each(function () {
                        //new YouTubePopUp($(this), $('.lightbox'), 640, 385);
                //});

                //$('#media .photo a').each(function () {
                        //new ImagePopUp($(this), $('.lightbox'), 640, 385);
                //});
        //}
        setupClickHandlers();

        
        /* MP3 Player */
	var playItem = 0;

	var myPlayList = [
		{name:"Well, You Might", mp3:"mp3/01_well_you_might.mp3"},
		{name:"Time For the Hard Stuff", mp3:"mp3/02_time_for_the_hard_stuff.mp3"},
		{name:"The Wizard", mp3:"mp3/03_the_wizard.mp3"},
		{name:"3-Legged Dance", mp3:"mp3/04_3-legged_dance.mp3"},
		{name:"This Ain't No Russian Novel, Baby", mp3:"mp3/05_this_aint_no_russian_novel_baby.mp3"},
                {name:"Doggie and Cookie", mp3:"mp3/06_doggie_and_cookie.mp3"},
                {name:"Roses", mp3:"mp3/07_roses.mp3"},
                {name:"Swirling Grimly", mp3:"mp3/08_swirling_grimly.mp3"},
                {name:"Sans Francisco", mp3:"mp3/09_sans_francisco.mp3"},
        ];

	function playListChange( index ) {
		$("#jquery_jplayer").jPlayer("setFile", myPlayList[index].mp3);
                $("#track_title").text(myPlayList[index].name);
		//$("#jquery_jplayer").jPlayer("play");
        }	

	function playListNext() {
		var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
                playItem = index;
		playListChange( index );
                $("#jquery_jplayer").jPlayer("play");
	}
        

	$("#jquery_jplayer").jPlayer({
                swfPath: "/js",
                warningAlerts: true,
		ready: function() {
                        playListChange(0);
		}
	})
	.jPlayer("onSoundComplete", function() {
		playListNext();
	});

        $("#play_btn").click(function(){
          $("#jquery_jplayer").jPlayer("play");
        });

        $("#stop_btn").click(function(){
          $("#jquery_jplayer").jPlayer("pause");
        });

        $("#next_btn").click(function(){
          playListNext();
        });

        function playAlbumTrack(title,track) {
        	$("#jquery_jplayer").jPlayer("setFile", track).jPlayer("play");
                $("#track_title").text(title);
        }

        function setupClickHandlers(){
          if ($('#media').length) {
            $('#media .video a').each(function(){
                $(this).unbind();
                new YouTubePopUp($(this),$('.lightbox'), 640, 385);
            });
            $('#media .photo a').each(function(){
                $(this).unbind();
                new ImagePopUp($(this),$('.lightbox'), 640, 385);
            });
          }
          if ($('#bio').length) {
                  $('#bio .col').each(function () {
                          new Toggler($(this).find('.view a'), $(this).find('.discography'));
                  });
          }
          if ($('#store').length) {
            $('h4').each(function() {
              $(this).click(function(){
                $(this).parents('form').submit();
              });
            });
            $('#content .btn.play').each(function(){
              $(this).click(function(){
                var mytrack = $(this).find('.album_track_info').attr('rel');
                var mytitle = $(this).find('.album_track_info').html();
                playAlbumTrack(mytitle, mytrack);
              });
            });

            $('#content .btn.pause').each(function(){
              $(this).click(function(){
                $('#jquery_jplayer').jPlayer('pause');
              });
            });
          }

          if ($('#fan_form').length) {
            $('#fan_form').ajaxForm({
              success: function(){
                $('#fan_form').fadeOut(500);
              },
              target: '#thank_you'
            });

          }
          if ($(".feed").length) {
            $(".feed").getTwitter({
                    userName: "dredscotttrio",
                    numTweets: 8,
                    loaderText: "Loading tweets...",
                    slideIn: false,
                    showHeading: false,
                    showProfileLink: false
            });
          }
        }

        $("#nav li.ajax a").click(function(){
          //$("#content").load("/shows");
          action = $(this).attr('rel');
          $.get('/' + action, function(data) {
            $('#content').hide();
            $('#content').html(data);
            $("body").attr("id", action);
            $("#content").fadeIn(500, function(){
              setupClickHandlers();
            });
          }, "script");
          return false;
        });

       // if($('#shows').length) {

          $(".shows_link").click(function(){
            action = $(this).attr('rel');
            $.get('/shows', function(data) {
              $('#content').hide();
              $('#content').html(data);
              $("body").attr("id", 'shows');
              $("#content").fadeIn(500, function(){
                setupClickHandlers();
              });
            }, "script");
            return false;
          
          })
        //}

});

