/**
 * jquery.uploadify.v2.1.0.min.js
 * director.js
 * typeWatch.js
 * jquery.hoverIntent.js
 * forms.js
 * browse.js
 * slider.js
 */

/*
Uploadify v2.1.0
Release Date: August 24, 2009

Copyright (c) 2009 Ronnie Garcia, Travis Nickels

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
if(jQuery){(function(a){a.extend(a.fn,{uploadify:function(b){a(this).each(function(){settings=a.extend({id:a(this).attr("id"),uploader:"uploadify.swf",script:"uploadify.php",expressInstall:null,folder:"",height:30,width:110,cancelImg:"cancel.png",wmode:"opaque",scriptAccess:"sameDomain",fileDataName:"Filedata",method:"POST",queueSizeLimit:999,simUploadLimit:1,queueID:false,displayData:"percentage",onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){},onAllComplete:function(){}},b);var e=location.pathname;e=e.split("/");e.pop();e=e.join("/")+"/";var f={};f.uploadifyID=settings.id;f.pagepath=e;if(settings.buttonImg){f.buttonImg=escape(settings.buttonImg)}if(settings.buttonText){f.buttonText=escape(settings.buttonText)}if(settings.rollover){f.rollover=true}f.script=settings.script;f.folder=escape(settings.folder);if(settings.scriptData){var g="";for(var d in settings.scriptData){g+="&"+d+"="+settings.scriptData[d]}f.scriptData=escape(g.substr(1))}f.width=settings.width;f.height=settings.height;f.wmode=settings.wmode;f.method=settings.method;f.queueSizeLimit=settings.queueSizeLimit;f.simUploadLimit=settings.simUploadLimit;if(settings.hideButton){f.hideButton=true}if(settings.fileDesc){f.fileDesc=settings.fileDesc}if(settings.fileExt){f.fileExt=settings.fileExt}if(settings.multi){f.multi=true}if(settings.auto){f.auto=true}if(settings.sizeLimit){f.sizeLimit=settings.sizeLimit}if(settings.checkScript){f.checkScript=settings.checkScript}if(settings.fileDataName){f.fileDataName=settings.fileDataName}if(settings.queueID){f.queueID=settings.queueID}if(settings.onInit()!==false){a(this).css("display","none");a(this).after('<div id="'+a(this).attr("id")+'Uploader"></div>');swfobject.embedSWF(settings.uploader,settings.id+"Uploader",settings.width,settings.height,"9.0.24",settings.expressInstall,f,{quality:"high",wmode:settings.wmode,allowScriptAccess:settings.scriptAccess});if(settings.queueID==false){a("#"+a(this).attr("id")+"Uploader").after('<div id="'+a(this).attr("id")+'Queue" class="uploadifyQueue"></div>')}}if(typeof(settings.onOpen)=="function"){a(this).bind("uploadifyOpen",settings.onOpen)}a(this).bind("uploadifySelect",{action:settings.onSelect,queueID:settings.queueID},function(j,h,i){if(j.data.action(j,h,i)!==false){var k=Math.round(i.size/1024*100)*0.01;var l="KB";if(k>1000){k=Math.round(k*0.001*100)*0.01;l="MB"}var m=k.toString().split(".");if(m.length>1){k=m[0]+"."+m[1].substr(0,2)}else{k=m[0]}if(i.name.length>20){fileName=i.name.substr(0,20)+"..."}else{fileName=i.name}queue="#"+a(this).attr("id")+"Queue";if(j.data.queueID){queue="#"+j.data.queueID}a(queue).append('<div id="'+a(this).attr("id")+h+'" class="uploadifyQueueItem"><div class="cancel"><a href="javascript:jQuery(\'#'+a(this).attr("id")+"').uploadifyCancel('"+h+'\')"><img src="'+settings.cancelImg+'" border="0" /></a></div><span class="fileName">'+fileName+" ("+k+l+')</span><span class="percentage"></span><div class="uploadifyProgress"><div id="'+a(this).attr("id")+h+'ProgressBar" class="uploadifyProgressBar"><!--Progress Bar--></div></div></div>')}});if(typeof(settings.onSelectOnce)=="function"){a(this).bind("uploadifySelectOnce",settings.onSelectOnce)}a(this).bind("uploadifyQueueFull",{action:settings.onQueueFull},function(h,i){if(h.data.action(h,i)!==false){alert("The queue is full.  The max size is "+i+".")}});a(this).bind("uploadifyCheckExist",{action:settings.onCheck},function(m,l,k,j,o){var i=new Object();i=k;i.folder=e+j;if(o){for(var h in k){var n=h}}a.post(l,i,function(r){for(var p in r){if(m.data.action(m,l,k,j,o)!==false){var q=confirm("Do you want to replace the file "+r[p]+"?");if(!q){document.getElementById(a(m.target).attr("id")+"Uploader").cancelFileUpload(p,true,true)}}}if(o){document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(n,true)}else{document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(null,true)}},"json")});a(this).bind("uploadifyCancel",{action:settings.onCancel},function(l,h,k,m,j){if(l.data.action(l,h,k,m,j)!==false){var i=(j==true)?0:250;a("#"+a(this).attr("id")+h).fadeOut(i,function(){a(this).remove()})}});if(typeof(settings.onClearQueue)=="function"){a(this).bind("uploadifyClearQueue",settings.onClearQueue)}var c=[];a(this).bind("uploadifyError",{action:settings.onError},function(l,h,k,j){if(l.data.action(l,h,k,j)!==false){var i=new Array(h,k,j);c.push(i);a("#"+a(this).attr("id")+h+" .percentage").text(" - "+j.type+" Error");a("#"+a(this).attr("id")+h).addClass("uploadifyError")}});a(this).bind("uploadifyProgress",{action:settings.onProgress,toDisplay:settings.displayData},function(j,h,i,k){if(j.data.action(j,h,i,k)!==false){a("#"+a(this).attr("id")+h+"ProgressBar").css("width",k.percentage+"%");if(j.data.toDisplay=="percentage"){displayData=" - "+k.percentage+"%"}if(j.data.toDisplay=="speed"){displayData=" - "+k.speed+"KB/s"}if(j.data.toDisplay==null){displayData=" "}a("#"+a(this).attr("id")+h+" .percentage").text(displayData)}});a(this).bind("uploadifyComplete",{action:settings.onComplete},function(k,h,j,i,l){if(k.data.action(k,h,j,unescape(i),l)!==false){a("#"+a(this).attr("id")+h+" .percentage").text(" - Completed");a("#"+a(this).attr("id")+h).fadeOut(250,function(){a(this).remove()})}});if(typeof(settings.onAllComplete)=="function"){a(this).bind("uploadifyAllComplete",{action:settings.onAllComplete},function(h,i){if(h.data.action(h,i)!==false){c=[]}})}})},uploadifySettings:function(f,j,c){var g=false;a(this).each(function(){if(f=="scriptData"&&j!=null){if(c){var i=j}else{var i=a.extend(settings.scriptData,j)}var l="";for(var k in i){l+="&"+k+"="+escape(i[k])}j=l.substr(1)}g=document.getElementById(a(this).attr("id")+"Uploader").updateSettings(f,j)});if(j==null){if(f=="scriptData"){var b=unescape(g).split("&");var e=new Object();for(var d=0;d<b.length;d++){var h=b[d].split("=");e[h[0]]=h[1]}g=e}return g}},uploadifyUpload:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").startFileUpload(b,false)})},uploadifyCancel:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").cancelFileUpload(b,true,false)})},uploadifyClearQueue:function(){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").clearFileUploadQueue(false)})}})})(jQuery)};

/** 
 * director.js
 */
$(document).ready(function () {
	$(".closeLink, .closeRightFormLink").click(function(event) {
		event.preventDefault();
		if ($("h6").attr("alt") == "") {
			$("h6").hide();
		}
		$('#rightForm').animate({right: "-320px"}, 'slow');
		$("h6").removeAttr('title');
		var theValueOfAlt = $("h6").attr("alt");
		$("h6").text(theValueOfAlt);
	});
	
	$('.noactor,.addBandLink,.addShowLink,.addVenueLink,.editAccountLink,.editBankLink,.editShowLink,.editVenueLink,.createAccountLink,.editBandLink,.editMediaLink,.editVenueLink,.editAccountLink, .addLiveLink, .editLiveLink').click(function(event) {
		event.preventDefault();
		$('html, body').animate({scrollTop:0}, 'slow');
		$('#four').fadeOut();
		if ($("h6").attr("title") == "closeForm") {
			if ($(this).attr("id") == "actor") {
				// Form open and actor clicked. close form, set title and right from to hide
				var theValueOfAlt = $("h6").attr("alt");
				if ($("h6").attr("alt") == "") {
					$("h6").hide();
				}
				$("h6").text(theValueOfAlt).removeAttr('title');
				$('#rightForm').stop().animate({right: '-320px'}, 'slow');
				$("h6").removeAttr("title");
				$("#theFormContent").html('Please wait while the form is loading...<br /><img class="center" src="/images/backgrounds/loader.gif">');
			}
			else {
				// Form open and non-actor clicked. close form quickly so that it can be reopened
				if ($("h6").attr("alt") == "") {
					$("h6").hide();
				}
				$('#rightForm').stop().animate({right: "-320px"}, 'slow');
				$("#theFormContent").html('Please wait while the form is loading...<br /><img class="center" src="/images/backgrounds/loader.gif">');
			}
		} else {
			// form closed, so set actor to Close and set title to close form
			if ($("h6").attr("alt") == "") {
				$("h6").show();
			}
			$("h6").text('CLOSE');
			$("h6").attr('title','closeForm');
		}
		
		if ($("h6").attr("title") == "closeForm") {
			// open the rightForm and ajax load the form
			$('#rightForm').stop().animate({right: 0}, 'slow');
			if ($("h6").attr("alt") == "") {
				$("h6").show();
			}
			var getFormName = $(this).attr('class'), theFormName = getFormName.replace(/ /g, '').toLowerCase();
			theFormName = theFormName.match(/.*?(?=.{4}$)/);
			
			if (theFormName == 'addshow') {
				theFormName = 'addmedia';
			}
			
			var currentAsset = $("#currentAssetId").val();
			var currentBand = $("#currentBandId").val();
			var currentVenue = $("#currentVenueId").val();
	
			var url = '/content/getform/text/' + escape(theFormName) + '/asset/' + escape(currentAsset) + '/band/' + escape(currentBand) + '/venue/' + escape(currentVenue);
			
			$.ajax({
			  url: url,
			  cache: false,
			  dataType: "json",
			  success: function(htmlPage){
				// var html = eval(json);
			  	if ((htmlPage) == null) {
					$("#theFormContent").html('Sorry, there was a problem loading the form');
				} else {
					$("#theFormContent").html(htmlPage);
				}
			  },
			  error: function(htmlPage) {
			  	 $("#theFormContent").html('Sorry, there was a problem loading the form. Please close the form and try again or refresh the entire page.');
			  }
			})
		};
	});
	
	// marquee Slider
	// reveal .main_view and .main_view_list to give time for loading
	// $('.main_view_list').fadeIn(2000);
	// $('#columnB').fadeIn(2000);
	//Set Default State of each portfolio piece
	$(".paging").show();
	$(".paging a:first").addClass("active");
		
	//Get size of images, how many there are, then determine the size of the image reel.
	var imageWidth = $(".window").width();
	
	if (imageWidth == null) {
		imageWidth = $(".window_list").width();
		if (imageWidth == null) {
			imageWidth = $(".window_tabslider").width();
			// imageWidth = imageWidth + 28; // reduce for margin
		}
	}
	var imageSum = $(".image_reel img").size();

	var imageReelWidth = imageWidth * imageSum;
	//Adjust the image reel to its new size
	$(".image_reel").css({'width': imageReelWidth});

	//Paging + Slider Function
	rotate = function(){	
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".paging a").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
		
		//Slider Animation
		$(".image_reel").animate({ 
			left: -image_reelPosition
		}, 500 );
		
	}; 
	
	//Rotation + Timing Event
	rotateSwitch = function(){		
		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
			$active = $('.paging a.active').next();
			if ( $active.length === 0) { //If paging reaches the end...
				$active = $('.paging a:first'); //go back to first
			}
			rotate(); //Trigger the paging and slider function
		}, 7000); //Timer speed in milliseconds (3 seconds = 7000)
	};
	
	rotateSwitch(); //Run function on launch
	
	// Left Arrow
	$(".leftArrow, #slider-navPrev").click(function() {
		if ($('.paging a:first').hasClass('active')) {
			$active = $('.paging a:last');
		} else {
			$active = $('.paging a.active').prev();
		}
		clearInterval(play);
		rotate();
		rotateSwitch();
		return false;
	});
	
	// Right Arrow
	$(".rightArrow, #slider-navNext").click(function() {
		if ($('.paging a:last').hasClass('active')) {
			$active = $('.paging a:first');
		} else {
			$active = $('.paging a.active').next();
		}
		clearInterval(play);
		rotate();
		rotateSwitch();
		return false;
	});
	
	// Arrow On Hover
	$(".image_reel a").hover(function() {
		clearInterval(play); //Stop the rotation
	}, function() {
		rotateSwitch(); //Resume rotation
	});	
	
	// Arrow On Click
	$(".paging a").click(function() {	
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});	
	
	if ($('.paging a').length == 1) {
		$('#slider-navPrev').addClass('slider-navPrevDisabled');
		$('#slider-navNext').addClass('slider-navNextDisabled');
		$('#slider-navPrev, #slider-navNext').click(function(event) {
			event.preventDefault();
		});
	}
	
	
	// INVITE MEMBER
	$('#newmember_invite').click(function(event){
		var inviteEmail = $('#newmember_email').val();
		var inviteBandId = $('#currentBandId').val();

		if (isValidEmailAddress(inviteEmail)) {
			$.ajax({
			type: 'Post',
			url: '/band/invite/',
			data: 'inviteBandId=' + inviteBandId +  '&email=' + inviteEmail,
			dataType: "json",
			success: function(json){
				if (json.success == true) {
					$('#inviteSuccess').hide().fadeIn('slow').addClass('error').html('email sent to ' + inviteEmail + '.<br />Go ahead and send another email to the next band member if you\'d like...');
					$('#newmember_email').val('');
				} else {
					if (json.reason == 'band admin email') {
						$('#inviteSuccess').hide().fadeIn('slow').addClass('error').html('** You cannot invite yourself to the band. You are the band admin.');
					} else if (json.reason == 'already member') {
						$('#inviteSuccess').hide().fadeIn('slow').addClass('error').html('** That email address is already a member of this band.');
					} else {
						$('#inviteSuccess').hide().fadeIn('slow').addClass('error').html('** there was an error. please try again.');
					}
				}
				setTimeout(function() {
					$('#inviteSuccess').fadeOut('slow', function() {
						$('inviteSuccess').hide();
						$('#newmember_email').val('');
					});
				}, 4000);
			}
		})
		} else {
			$('#inviteSuccess').hide().fadeIn('slow').addClass('error').html('Please enter a vaild email address.');
		}
	});
	
	// DEACTIVATE / REACTIVATE ASSET - DisAssociate / associate member
	$('.deactivate, .reactivate, .disassociate, .associate').click(function(event) {
		$(this).css('color','gold');
		var currentAsset = $(this).attr('alt');
		var whichWay = $(this).text();
		$.ajax({
			type: 'Post',
			url: '/band/editmembermedia/',
			data: 'id=' + currentAsset + '&whichWay=' + whichWay,
			dataType: "json",
			async: false,
			success: function(obj){
				if (obj.whichWay == 'deactivate') {
					$('#' + obj.id).effect('transfer', { to: "#manage-band-media", className: 'ui-effects-transfer' }, 500).fadeOut('fast');
					$('#' + obj.id + '> a:first').text('reactivate').css({color: 'green'});
					$('#' + obj.id).fadeIn('slow');
				} else if (obj.whichWay == 'reactivate') {
					$('#' + obj.id).effect('transfer', { to: "#manage-band-media", className: 'ui-effects-transfer' }, 500).fadeOut('fast');
					$('#' + obj.id + '> a:first').text('deactivate').css({color: 'purple'});
					$('#' + obj.id).fadeIn('slow');
				} else if (obj.whichWay == 'disassociate') {
					$('#memberId-' + obj.id).effect('transfer', { to: "#band-members", className: 'ui-effects-transfer' }, 500).fadeOut('fast');
					$('#memberId-' + obj.id + '> a:first').text('associate').css({color: 'green'});
					$('#memberId-' + obj.id).fadeIn('slow');
				} else if (obj.whichWay == 'associate') {
					$('#memberId-' + obj.id).effect('transfer', { to: "#band-members", className: 'ui-effects-transfer' }, 500).fadeOut('fast');
					$('#memberId-' + obj.id + '> a:first').text('disassociate').css({color: 'purple'});
					$('#memberId-' + obj.id).fadeIn('slow');
				} else {
					alert('Oops. Sorry there was an error. Please contact Stagedive for assistance or try again.');
				}
			},
			error: function(){
				alert('Oops. There was an AJAX error. Please try again.');
			}
		});
	});
	
	$('.vodAssetPlayerMoreInfo').toggle(function(event){
		event.preventDefault();
		$('#twentyone').css({
			'background': '#222',
			'box-shadow': '2px 2px 6px 3px #999',
 			'-moz-box-shadow': '2px 2px 6px 3px #999',
 			'-webkit-box-shadow': '2px 2px 6px 3px #999'
		});
		$('#twentyoneTop').css({
			'height': '100%',
			'overflow-y': 'auto',
			'margin-bottom': 20
		}).animate({'max-height': 700}, 500);
		$('.vodAssetPlayerMoreInfo a').text('Close Info Box');
	}, function(event){
		$('#twentyoneTop').css({
			'overflow-y': 'hidden',
			'margin-bottom': 0
		}).animate({height: 340, scrollTop: 0}, 500, function(){
			$('#twentyone').css({
				'background': 'none',
				'box-shadow': 'none',
 				'-moz-box-shadow': 'none',
 				'-webkit-box-shadow': 'none'
			});	
		});
		var currentBandText = $('.vodAssetPlayerMoreInfo a').attr('alt');
		$('.vodAssetPlayerMoreInfo a').text('Read more about ' + currentBandText);
	});
	
	$('.assetPopupTrigger').live('click',function(){
		$('#assetPopupContainer').hide();
	})
	
	
	$('#assetTooltipClose').live('click',function() {
		$('#assetPopupContainer').hide();
	});
	
	$('#media_keepalive[type=checkbox][checked]').live('click',function() {
		alert('currently disabled');
	});
	
});

/*
Break
*/
$.fn.exists = function(){return $(this).length>0;}
$.fn.notExists = function(){return $(this).length<0;}
$("a[href^=http://]").attr("target","_blank");
/*
Break
*/
// ASSET TOOLTIP
$(function()
{
    var hideDelay = 500;
    var hideTimer = null;
    var ajax = null;
    var hideFunction = function()
    {
        if (hideTimer)
            clearTimeout(hideTimer);
        hideTimer = setTimeout(function()
        {
            currentPosition = { left: '0px', top: '0px' };
            container.css('display', 'none');
        }, hideDelay);
    };

    var currentPosition = { left: '0px', top: '0px' };

    // One instance that's reused to show info for the current asset
    var container = $('<div id="assetPopupContainer">'
        + '<table width="" border="0" cellspacing="0" cellpadding="0" align="center" class="assetPopupPopup">'
        + '<tr>'
        + '   <td class="corner topLeft"></td>'
        + '   <td class="top"></td>'
        + '   <td class="corner topRight"></td>'
        + '</tr>'
        + '<tr>'
        + '   <td class="left">&nbsp;</td>'
        + '   <td><div id="assetPopupContent"></div></td>'
        + '   <td class="right">&nbsp;</td>'
        + '</tr>'
        + '<tr>'
        + '   <td class="corner bottomLeft">&nbsp;</td>'
        + '   <td class="bottom">&nbsp;</td>'
        + '   <td class="corner bottomRight"></td>'
        + '</tr>'
        + '</table>'
        + '</div>');

    $('body').append(container);
    $('.assetPopupTrigger').live('mouseover', function()
    {
        if (!$(this).data('hoverIntentAttached'))
        {
            $(this).data('hoverIntentAttached', true);
            $(this).hoverIntent
            (
                // hoverIntent mouseOver
                function()
                {
                    if (hideTimer)
                        clearTimeout(hideTimer);

                    // format of 'rel' tag: assetId,assetguid
                    var settings = $(this).attr('href').split('/');
					var queryType = settings[2];
					if(queryType == 'videos') {
						queryType = 'asset';
					} else {
						queryType = 'band';
					}
					if (settings[1] == 'venues') {
						queryType = 'venue';
					}
					
                    var assetId = settings[3];
					var assetTitle = $(this).attr('title');
					var bandIdent = settings[1];
					var venueIdent = settings[2];
                    var pos = $(this).offset();
                    var width = $(this).width();
                    var reposition = { left: (pos.left + width) + 'px', top: pos.top - 95 + 'px' };

                    // If the same popup is already shown, then don't requery
                    if (currentPosition.left == reposition.left &&
                        currentPosition.top == reposition.top)
                        return;

                    container.css({
                        left: reposition.left,
                        top: reposition.top
                    });

                    currentPosition = reposition;

                    $('#assetPopupContent').html('<div style="margin: 0 auto; text-align: center;"><img src="/images/backgrounds/loader.gif" style="text-align: center;"</div><div style="margin: 0 auto;">Loading additional information</div>');

					if (ajax)
					{
					    ajax.abort();
					    ajax = null;
					}

		            ajax = $.ajax({
		                type: 'POST',
		                url: '/asset/tooltip/',
		                data: 'assetId=' + assetId + '&bandIdent=' + bandIdent + '&venueIdent=' + venueIdent + '&queryType=' + queryType,
						dataType: "json",
		                success: function(data)
		                {
		                    // Verify requested asset is this asset since we could have multiple ajax
		                    // requests out if the server is taking a while.
		                    //if (data.assetId == assetId)
		                    //{
		                        $('#assetPopupContent').html(data.theContent);
		                    //}
		                }
		            });

                    container.css('display', 'block');
                },
                // hoverIntent mouseOut
                hideFunction
            );
            // Fire mouseover so hoverIntent can start doing its magic
            $(this).trigger('mouseover');
        }
    });

    // Allow mouse over of details without hiding details
    $('#assetPopupContainer').mouseover(function()
    {
        if (hideTimer)
            clearTimeout(hideTimer);
    });

    // Hide after mouseout
    $('#assetPopupContainer').mouseout(hideFunction);
});
/*
Break
*/
// Lock a submit button when clicked from being clicking again and change the value of the submit to a message, while preserving the submits name and value in a hidden input.
// License: http://www.gnu.org/licenses/lgpl.txt
// Homepage: http://blog.leenix.co.uk/2009/09/jquery-plugin-locksubmit-stop-submit.html
// Version 1.03

jQuery.fn.lockSubmit = function(options) {

	//Default text to change submit button too
	var settings = jQuery.extend({
		submitText: 'Please wait... processing',
		onAddCSS: null,
		onClickCSS: null
	}, options);

	//add CSS to this button
	if(settings.onAddCSS) {	this.addClass(settings.onAddCSS); }

	return this.click(function(e) {		

		//Hide current submit and insert a dummy submit which is disabled. The reason for doing this and not just disabling the normal submit, is that in some browsers the disabled submit will stop the form being submited at all.

		targetselect = jQuery(this);

		targetselect.hide();
		
		//new buttons value
		if(settings.submitText) { var newValue = settings.submitText; } else { var newValue = jQuery(this).val(); }

		//insert hidden field with name and value of submit
		targetselect.after("<input id='dummySubmit' disabled='disabled' type='submit' name='"+jQuery(this).attr("name")+"DUMMY' value='"+newValue+"'>");

		//add onClick CSS
		if(settings.onClickCSS) {
			jQuery("#dummySubmit").addClass(settings.onClickCSS);
		}

		return true;
	});

};

jQuery.fn.lockSubmitReset = function() {
	this.show();
	jQuery("#dummySubmit").remove();
};

/**
 * typeWatch.js
 */
/*
 *	TypeWatch 2.0 - Original by Denny Ferrassoli / Refactored by Charles Christolini
 *
 *	Examples/Docs: www.dennydotnet.com
 *	
 *  Copyright(c) 2007 Denny Ferrassoli - DennyDotNet.com
 *  Coprright(c) 2008 Charles Christolini - BinaryPie.com
 *  
 *  Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
*/

(function(jQuery) {
	jQuery.fn.typeWatch = function(o){
		// Options
		var options = jQuery.extend({
			wait : 750,
			callback : function() { },
			highlight : true,
			captureLength : 2
		}, o);
			
		function checkElement(timer, override) {
			var elTxt = jQuery(timer.el).val();
		
			// Fire if text > options.captureLength AND text != saved txt OR if override AND text > options.captureLength
			if ((elTxt.length > options.captureLength && elTxt.toUpperCase() != timer.text) 
			|| (override && elTxt.length > options.captureLength)) {
				timer.text = elTxt.toUpperCase();
				timer.cb(elTxt);
			}
		};
		
		function watchElement(elem) {			
			// Must be text or textarea
			if (elem.type.toUpperCase() == "TEXT" || elem.nodeName.toUpperCase() == "TEXTAREA") {

				// Allocate timer element
				var timer = {
					timer : null, 
					text : jQuery(elem).val().toUpperCase(),
					cb : options.callback, 
					el : elem, 
					wait : options.wait
				};

				// Set focus action (highlight)
				if (options.highlight) {
					jQuery(elem).focus(
						function() {
							this.select();
						});
				}

				// Key watcher / clear and reset the timer
				var startWatch = function(evt) {
					var timerWait = timer.wait;
					var overrideBool = false;
					
					if (evt.keyCode == 13 && this.type.toUpperCase() == "TEXT") {
						timerWait = 1;
						overrideBool = true;
					}
					
					var timerCallbackFx = function()
					{
						checkElement(timer, overrideBool)
					}
					
					// Clear timer					
					clearTimeout(timer.timer);
					timer.timer = setTimeout(timerCallbackFx, timerWait);				
										
				};
				
				jQuery(elem).keydown(startWatch);
			}
		};
		
		// Watch Each Element
		return this.each(function(index){
			watchElement(this);
		});
		
	};

})(jQuery);

/**
 * @author http://cherne.net/brian/resources/jquery.hoverIntent.js
 */
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @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) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			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; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

/**
 * forms.js
 */
function isValidEmailAddress(email) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(email);
}

$(document).ready(function () {
	// top login form
	$('.loginField :input').focus(function(event) {
		$(this).parent().css("border-left","5px solid #FFA500");
		$(this).next('.loginFieldInfo').fadeIn('slow');
	}).blur(function(event) {
		$(this).parent().css("border-left","5px solid #666666");
		$(this).next('.loginFieldInfo').fadeOut('slow');
	});

	if ($('#theFormContent').hasClass('lightboxActive')) {
		$("h6").text('CLOSE');
		$("h6").attr('title','closeForm');
	}
	
	// display Right Form Field Informer, hide on load
	$('.fieldInformer').hide();
	$('.rightFormField :input, .rightFormFieldTextArea :input, .rightFormFieldFile :input, .rightFormFieldFile :button, .rightFormFieldFile :file').live('focus',function(event) {
		$(this).parent().css("border-left","5px solid #FFA500");
		$(this).siblings().next('.fieldInformer').slideToggle('fast');
	}).live('blur',function(event) {
		$(this).parent().css("border-left","5px solid #666666");
		$(this).siblings().next('.fieldInformer').slideToggle('fast');
	});
	
	$('.exitRightForm').live('click',function() {
	var answer = confirm('The current form data and/or upload will be cancelled if you continue. Do you want to continue?');
	return answer;
	});
	
	//Hide (Collapse) the toggle containers on load 
	$(".toggle_container").hide();
	$('.onlyOne').show();
	
	//Slide up and down & toogle the Class on click
	$('h2.trigger').live('click',function(){
	$(this).toggleClass('active').next('.toggle_container').slideToggle('slow');
	});
	
	// JOIN FORM
	$('#email').live('blur', function() {
		var email = $('#email').val();
		if (isValidEmailAddress(email)) {
			$('#email').css('none');
			$('#badEmailError').remove();
			$.ajax({
				type: 'Post',
				url: '/login/emailcheck/',
				data: 'email=' + email,
				dataType: "json",
				success: function(obj){
					if (obj.error == 'true') {
						$('#email').css('outline','thin dashed red').addClass('empty').addClass('badEmailError');
						$('#emailError').remove();
						$('#account_error').append("<div id='emailError'>" + obj.text + "<a href='/login/resetpassword' style='padding-left:10px;'>Reset Password</a>");
					} else {
						$('#email').css('outline','none');
						$('#email').removeClass('empty');
						$('#email').removeClass('badEmailError');
						$('#emailError').remove();
					}
				}
			})
		} else { // if not a Valid Email Address
			$('#email').css('outline','thin dashed red').addClass('empty').addClass('badEmailError');
			$('#badEmailError').remove();
			$('#account_error').append("<div id='badEmailError'>* Valid Email Address is Required</div>");
		}
	});
	
	// Contact us email check
	$('#contactemail').blur(function() {
		var contactemail = $('#contactemail').val();
		if (isValidEmailAddress(contactemail)) {
			$('#contactemailerror').hide();
			$('#contactNoSubmit').val(0);
		} else { // if not a Valid Email Address
			$('#contactemailerror').show();
			$('#contactNoSubmit').val(1);
		}
	});
	$('#submit_contact').click(function(event) {
		if ($('#contactNoSubmit').val() == 1) {
			event.preventDefault();
			$('#contactemailerror').fadeOut('slow').delay(500).fadeIn('slow');
		}
	});
	$('#confirm_password').live('keyup',function() {
		if ($('#password_form').val() != $('#confirm_password').val()) {
			$('#confirm_password').css('outline','thin dashed red');
			$('#confirm_passworderror').remove();
			$('#account_error').append('<div id="confirm_passworderror">* Your passwords did not match<br /></div>');
			$('#confirm_password').addClass('empty');
		} else {
			$('#confirm_password').css('outline','none');
			$('#confirm_passworderror').remove();
			$('#confirm_password').removeClass('empty');
		}
	});
	
	$('.required').live('blur',function() {
		$('#submit_error').remove();
		var currentField = $(this).attr('title'),
			currentFieldNoSpaces = currentField.replace(/ /g,'').toLowerCase();
		if ($(this).val() == '') {
			$('#' + currentFieldNoSpaces + 'Error').remove();
			$(this).css('outline','thin dashed red');
			$(this).addClass('empty');
			$('#account_error').append('<div id="' + currentFieldNoSpaces + 'Error">* ' + currentField + ' is Required<br /></div>');
		} else {
			$(this).css('outline','none');
			$('#' + currentFieldNoSpaces + 'Error').remove();
			$(this).removeClass('empty');
		}
		if ($(this).hasClass('badEmailError')) {
			$(this).css('outline','thin dashed red');
		}
	});
	
	$('#service').live('click',function() {
	if ($('#service').attr("unchecked")) {
		$('#service').removeAttr("unchecked");
		$('#service').css('outline','none');
		$('#serviceError').remove();
		$('#service').val('1');
	} else {
		$('#service').attr("unchecked","unchecked");
		$('#service').val('0');
	}
});

	Browse.checkEmailInvite = function (email) {
		ajax('/login/emailcheck/ajax/true/email/' + email, null, Browse.errorInviteDisplay);
	}

	
	Browse.errorInviteDisplay = function (obj) {
		try {
			if (obj) {	
				if (obj.error == 'true') {
					$('#joinaccount_submit').css('display', 'none');
					$('#joinaccount_error').html(obj.text + "<a href='/login/resetpassword' style='padding-left:10px;'>Reset Password</a>");
				}
				else {
					$('#joinaccount_submit').css('display', 'block');
				 	$('#joinaccount_error').html('');
				}
			}
			else {
		
			}
		}
		catch(e) {
			alert("error" + e.message);
		}
	}
	
	// Edit Form
	$('#editPersonal').show();
	$('#editPersonalBar').addClass('active');
	
	$('#editPersonal').show();
	$('#editPersonalBar').addClass('active');
	
	$("#dob").datepicker({
		showOptions: {direction: 'top right'},
		changeMonth: true,
		changeYear: true,
		dateFormat: 'mm-dd-yy',
		yearRange: (new Date()).getFullYear()-100 + ':' + (new Date()).getFullYear(),
		maxDate: '-13y',
		onSelect: function() {
			$('#doberror').remove();
			$('#dob').addClass('empty');
			$('#submit_error').remove();
		},
		onClose: function(){
			if ($('#dob').val() == '') {
				$('#dob').css('outline','thin dashed red');
				$('#dateofbirthError').remove();
				$('#account_error').append('<div id="dateofbirthError">* Date of Birth is Required<br /></div>');
			} else {
				$('#dob').css('outline','none');
				$('#dateofbirthError').remove();
				$('#dob').removeClass('empty');
				$('#dob').focus();
			}
		}
	});
	
	
	$('#editaccount_submit').click(function(event) {
		var errors = 0;
		// check if required fields are empty
		$('.required').each(function(){
			var currentField = $(this).attr('title'),
				currentFieldNoSpaces = currentField.replace(/ /g,'').toLowerCase();
			if ($(this).hasClass('empty')) {
				errors++;
				$('#' + currentFieldNoSpaces + 'Error').remove();
				$(this).css('outline','thin dashed red');
				$(this).addClass('empty');
				$('#account_error').append('<div id="' + currentFieldNoSpaces + 'Error">* ' + currentField + ' is Required<br /></div>');
			}
		})
		
		// verify DOB - checks if empty and over 13 years old
		var dobEntered = $('#dob').val();
		dobEntered = dobEntered.replace('/', '');
		dobEntered = dobEntered.replace('/', '');
		dobEntered = dobEntered.replace('-', '');
		dobEntered = dobEntered.replace('-', '');
		
		var url = '/asset/dobentered/checkdate/' + escape(dobEntered);
		$.ajax({
			url: url,
			async: false,
			cache: false,
			dataType: "json",
			success: function(json){
				if (json.valid == "false") {
					$('#dateofbirthError').remove();
					$('#account_error').append('<div id="dateofbirthError">* Date of Birth is Required —<br />&nbsp;&nbsp;&nbsp;&nbsp;You must be at least 13 years old</div>');
					$('#dob').css('outline', 'thin dashed red');
					$('#dob').addClass('empty');
					errors++;
				} else {
					$('#submit_error').remove();
				}
			}
		});
		//process errors
		if (errors > 0) {
		 	event.preventDefault();
			$('#submit_error').remove();
			$('.empty').css('outline', 'thin dashed red');
			if (errors > 1) {var errorNoun = 'snags'} else {var errorNoun = 'snag'}
		 	$('#verification_error').append('<div id="submit_error">* Opps. ' + errors + ' ' + errorNoun +' stopped our progress.<br />&nbsp;&nbsp;Please review the required fields outlined in red<br /></div>');
		} else {
			 $(":submit",this).attr("disabled","disabled");
			 // event.preventDefault();
		}
	});	
	
	// BAND FORM
	 $('#sound').live('keyup',function(event) {
       var inputText = $('#sound').val(); 
       var sixWords = inputText.split(' ').length
		if (sixWords > 6) {
			alert('Please enter only six words for Band: Sounds Like');
		}
    });
	
	// NEWS FORM
	$("#date_published,#date_end").datepicker({
		inline: true,
		changeMonth: true,
		changeYear: true
	}).one('click', function(event) {
		$(this).val('');
	});
	$("#update_date_publishd,#update_date_end").live('click',function(){
		$(this).datepicker({
			inline: true,
			changeMonth: true,
			changeYear: true
		}).one('click', function(event) {
			$(this).val('');
		});
	});
	$('#update_date_published,#update_date_end').live('click', function() {
		$(this).datepicker({
			showOn:'focus',
			inline: true,
			changeMonth: true,
			changeYear: true
		}).focus().datepicker('show');
	});

	var newsListRequest = null;
	function getNewsList() {
		$('#newsList').html("<img class='center' src='/images/backgrounds/loader.gif'>");
		if (newsListRequest) {
			newsListRequest.abort();
			newsListRequest = null;
		}
		newsListRequest = $.ajax({
			type: 'get',
			url: '/news/getnewslist/',
			cache: false,
			dataType: 'json',
			success: function(json) {
				$('#newsList').html(json.html);
			}
		});
	}
	
	$('#createNews').click(function() {
		$('#formNewsCreate').show();
		$('#newsList').hide();
		$('html, body').animate({scrollTop:0}, 'fast');
		$('#headline').focus();
	});
	
	$('#listNews').click(function() {
		$('#formNewsCreate').hide();
		$('#newsList').show();
		$('html, body').animate({scrollTop:0}, 'fast');
		getNewsList();
	});
	var updateNewsRequest = null;
	$('.updateStory').live('click',function(event){
		$storyInfo = $(this).attr('rel').split('-');
		var currentNewsId = $storyInfo[0],
			headline = $storyInfo[1];
		$('#newsList').html("<img class='center' src='/images/backgrounds/loader.gif'>");
		if(updateNewsRequest) {
			updateNewsRequest.abort();
			updateNewsRequest = null;
		}
		updateNewsRequest = $.ajax({
			type: 'get',
			url: '/news/updatenews',
			data: 'currentNewsId=' + currentNewsId,
			cache: false,
			dataType: 'json',
			success: function(json) {
				$('#newsList').html(json.html);
			},
			error: function(json) {
				alert('Could not retreive News item');
				getNewsList();
			}
		});
	});
	$('.deleteStory').live('click',function(event) {
		$storyInfo = $(this).attr('rel').split('-');
		var currentNewsId = $storyInfo[0],
			headline = $storyInfo[1],
			url = '/news/newsstop/',
			answer = confirm('Are you sure you want to delete: ' + headline);
		if (answer == true) {
			$.ajax({
				type: 'Post',
				url: url,
				data: 'currentNewsId=' + currentNewsId,
				dataType: "json",
				success: function(json){
					getNewsList();
				},
				error: function(json){
					alert('Oops. Sorry there was an error.');
				}
			})
		}
	});
	
	$('#add_news').click(function(event){
		if($('#headline').val() == '' | $('#content').val() == '') {
			event.preventDefault();
			alert('Headline and Content can not be empty');
		}
	});
	
	$('.orderBox').live('change',function(event){
		var newOrder = $(this).val(),
			newsInfo = $(this).attr('id').split('-');
			currentId = newsInfo[1],
			newsOrderRequest = null;
		$('#newsList').html("<img class='center' src='/images/backgrounds/loader.gif'>");
		if (newsOrderRequest) {
			newsOrderRequest.abort();
			newsORderRequest = null;
		}
		newsOrderRequest = $.ajax({
			type: 'post',
			url: '/news/order/',
			data: 'currentNewsId=' + currentId + '&order=' + newOrder,
			cache: false,
			dataType: 'json',
			success: function(json) {
				getNewsList();
			},
			error: function(json) {
				alert('Oops. Could not reorder news list');
			}
		});
	})
});

/**
 * browse.js
 */
/**
 * @author Kent
 */

var Browse = {};
var quickSearchRequest = null;

function runQuickSearch() {
	var doRequest = true;
	var newLocation;
	var userId;
	var forward;
	
	if (quickSearchRequest) {
		quickSearchRequest.abort();
		quickSearchRequest = null;
	}
	
	var picks = $('#browse_picks').val(),
		live = $('#browse_live').val(),
		genre = $('#browse_genre :selected').val(),
		venue = $('#browse_venue :selected').val(),
		thumbnails = $('#browse_thumbnails').val(),
		sort = $('#browse_sort').val(),
		text = $('#browse_videoSearch').val(),
		page = $('#paginationInput').val(),
		searchType = $('#searchType').val(),
		searchId = $('#searchId').val(),
		currentId = $('#currentId').val();
	var picksOn;
	var liveOn;
	var venueOn;
	var genreOn;
	var url;
	if (picks == 1){picksOn = "<div style='clear: both; padding: 15px; font-size: 14px; font-weight: normal;'><span style='font-weight: bold; color:red;'>Hint: PICKS FILTER ON</span><br />The Stagedive Picks Filter is on. What we like, may not be exactly what you like. Turning the Picks filter off may provide more results.<br /><a href='#'>Click to search again without PICKS</a></div>";}
	if (live == 1) {liveOn = "<div style='clear: both; padding: 15px; font-size: 14px; font-weight: normal;'><span style='font-weight: bold; color:red;'>Hint: LIVE FILTER ON</span><br />The Live and Upcoming Live Show Filter is on. It appears there are no upcoming or currently live shows for this search query. Turning the Live filter off may provide more results.<br /><a href='#'>Click to search again without UPCOMING LIVE</a></div>";}
	if (venue > 1) {venueOn = "<div style='clear: both; padding: 15px; font-size: 14px; font-weight: normal;'><span style='font-weight: bold; color:red;'>Hint: VENUE FILTER ON</span><br />The Venue Filter is on. We just wanted to remind you. Turning the Venue filter off may provide more results.<br /><a href='#'>Click to search again without VENUE FILTER</a></div>";}
	if (genre > 0) {genreOn = "<div style='clear: both; padding: 15px; font-size: 14px; font-weight: normal;'><span style='font-weight: bold; color:red;'>Hint: GENRE FILTER ON</span><br />The Genre Filter is on. We just wanted to remind you. Turning the Genre filter off may provide more results.<br /><a href='#'>Click to search again without GENRE FILTER</a></div>";}
	
	checkText = text.toLowerCase();
	if (checkText === "all bands") {
		url = '/band/quicksearch/no/route';
	}
	else if (checkText === "all venues") {
		url = '/venue/quicksearch/no/route';
	} 
	else if (checkText === 'all shows') {
		url = '/asset/quicksearchgetall/no/route';
		text = '';
	}
	//else if (searchType === 'venueindex') {
	//	url = '/asset/quicksearchvenue/no/route';
	//}
	//else if (searchType === 'userindex') {
	//	url = '/asset/quicksearchuser/no/route'
	//}
	//else if ((searchType === 'bandindex') || (searchType === 'assetindex')) {
		//url = '/asset/quicksearchprofile/no/route';
	//}
	else {
		url = '/asset/quicksearch/no/route';
	}
	
	if (doRequest != false) {
		$('.fourteen').hide();
		$('#mediaList').html("<div id='loadingResults' style='padding: 10px; font-weight: bold; font-size: 30px; text-align: center;'>Retrieving Results...<br /><img class='center' src='/images/backgrounds/loader.gif'></div>");
		$('.assetPopupTrigger').hide();
		$('.searchAgainNoPicks').html('');
		$('.searchAgainNoLive').html('');
		$('html, body').animate({scrollTop:360}, 'slow');
		quickSearchRequest = $.ajax({
			type: 'Post',
			url: url,
			data: 'text=' + text + '&picks=' + picks + '&live=' + live + '&thumbnails=' + thumbnails + '&genre=' + genre + '&venue=' + venue + '&sort=' + sort  + '&page=' + page + '&searchId=' + searchId + '&currentId=' + currentId,
			dataType: "json",
			success: function(json){
				if (json.html == null) {
					$('#mediaList').html("<div id='noResults' style='padding: 10px; font-weight: bold; font-size: 30px;'>No Results...<br />Please try your search again.</div>");
					if (json.browseResponse) {
						$('#mediaList').append(json.browseResponse);
					}
					$('#searchType').val('normal');
				}
				else {
					$('#mediaList').html(json.html);
					$('#searchType').val(json.searchType)
					if (json.filtersOn == 1) {
						$('.searchAgainNoPicks').html(picksOn);
						$('.searchAgainNoLive').html(liveOn);
						$('.searchAgainNoGenre').html(genreOn);
						$('.searchAgainNoVenue').html(venueOn);
					}
					if (json.searchTerms == '') {
						searchTerms = 'All Shows';
					} else {
						searchTerms = json.searchTerms;
					}
					if (json.pageInfo["totalItemCount"] > 0) {
						// Top Results Bar
						$('#noBrowseResults').hide();
						$('#hasBrowseResults').show();
						$('#firstResult').text(json.pageInfo["firstItemNumber"]);
						$('#lastResult').text(json.pageInfo["lastItemNumber"]);
						$('#totalResultCount').text(json.pageInfo["totalItemCount"]);
						$('.originalSearchTerms').html('<strong>' + searchTerms + '</strong>');
						
						// Bottom Results Nav
						if (json.pageInfo["pageCount"] > 1) {
							$('#pagePoss').text('pages');
							$('#paginationInput').removeAttr('disabled');
							$('.showResultsNavGroup').addClass('activeColor').removeClass('inactiveColor');
							$('#paginationLast').addClass('browse-navLast').removeClass('browse-navLastInactive');
							if (json.pageInfo["current"] != 1) {
								$('#paginationFront').addClass('browse-navFront').removeClass('browse-navFrontInactive');
								$('#paginationPrev').addClass('browse-navPrev').removeClass('browse-navPrevInactive');
							} else {
								$('#paginationFront').addClass('browse-navFrontInactive').removeClass('browse-navFront');
								$('#paginationPrev').addClass('browse-navPrevInactive').removeClass('browse-navPrev');
								$('#paginationNext').addClass('browse-navNext').removeClass('browse-navNextInactive');
							}
							if (json.pageInfo["current"] == json.pageInfo["last"]) {
								$('#paginationNext').addClass('browse-navNextInactive').removeClass('browse-navNext');
							} else {
								$('#paginationNext').addClass('browse-navNext').removeClass('browse-navNextInactive');
							}
						} else {
							$('#paginationFront').addClass('browse-navFrontInactive').removeClass('browse-navFront');
							$('#paginationPrev').addClass('browse-navPrevInactive').removeClass('browse-navPrev');
							$('#paginationNext').addClass('browse-navNextInactive').removeClass('browse-navNext');
							$('#paginationLast').addClass('browse-navLastInactive').removeClass('browse-navLast');
							$('#paginationInput').attr('disabled','disabled');
							$('.showResultsNavGroup').addClass('inactiveColor').removeClass('activeColor');
							$('#pagePoss').text('page');
						}
						$('#paginationInput').val(json.pageInfo["current"]);
						$('#paginationLast').text(json.pageInfo["last"]);
					} else {
						$('#noBrowseResults').show();
						$('#hasBrowseResults').hide();
						$('.originalSearchTerms').html('<strong>' + searchTerms + '</strong>');
						// Bottom No Results
						$('#pagePoss').text('pages');
						$('#paginationInput').val('0').attr('disabled','disabled');
						$('#paginationLast').text('0');
						$('.showResultsNavGroup').addClass('inactiveColor').removeClass('activeColor');
						$('#paginationFront').addClass('browse-navFrontInactive').removeClass('browse-navFront');
						$('#paginationPrev').addClass('browse-navPrevInactive').removeClass('browse-navPrev');
						$('#paginationNext').addClass('browse-navNextInactive').removeClass('browse-navNext');
						$('#paginationLast').addClass('browse-navLastInactive').removeClass('browse-navLast');
					}
				}
				quickSearchRequest = null;
			},
			error: function(json){
				$('#mediaList').html("<div id='errorResults' style='padding: 10px; font-weight: bold; font-size: 30px; text-align: center;'>NO. Oops. There was a server error. Please try the search again...</div>");
			}
		})
	} else if (forward == true){
		$('.fourteen').hide();
		$('#mediaList').html("<div id='forwardSearch' style='padding: 10px; font-weight: bold; font-size: 30px; text-align: center;'>Retrieving \"" + text + "\"...<br />One moment while a new page loads the results<br /><img class='center' src='/images/loader.gif'></div>");
		$('.assetPopupTrigger').hide();
		window.location = newLocation;
	} else {
		alert('cancel request');
		$('#browse_videoSearch').val('').focus();
	}
};

$(document).ready(function(){	
	$('.advancedSearchLink a').click(function(event) {
		event.preventDefault();
		$('#advancedOptions').slideDown('slow');
		$('.advancedSearchLink a').fadeOut('slow', function() {
			$(this).text('');
		});
	});
	$('.advancedSearchInsideLink').click(function(event) {
		event.preventDefault();
		$('#advancedOptions').slideUp('slow');
		$('.advancedSearchLink a').fadeIn('slow', function() {
			$(this).text('Advanced Search');
		});
		$('#browse_genre option:nth(0)').attr('selected','selected');
		$('#browse_venue option:nth(0)').attr('selected','selected');
		$('#browse_sort option:nth(0)').attr('selected','selected');
		$('#browse_picks, #browse_live').val(0).attr('unchecked','unchecked');
		$('#browse_thumbnails').val(1).attr('checked','checked');
		$('.searchAgainNoPicks').html('');
		$('.searchAgainNoLive').html('');
		$('.searchAgainNoGenre').html('');
		$('.searchAgainNoVenue').html('');
	});
	
	$('#magglass').click(function(event) {
		runQuickSearch();
	});
	
	// typeWatch Settings
	var browseOptions = {
	    callback:function(e){ 
			runQuickSearch();
			$('#searchType').val('normal');
		},
	    wait:500,
	    highlight:true,
	    captureLength:0
	}
	// BROWSE FORM
	$('#browse_videoSearch').typeWatch(browseOptions).click(function() {
		if ($(this).val() == 'Browse Videos Here') {
			$(this).val('').focus();
		}
	});

	$('#browse_picks, #browse_live, #browse_thumbnails').click(function(){
		if($(this).val() == 1) {
			$(this).val(0);
			$('.searchAgainNoPicks').html('');
			$('.searchAgainNoLive').html('');
		} else {
			$(this).val(1);
		}
		runQuickSearch();
	});
	
	$('#browse_genre, #browse_venue, #browse_sort').change(function(){
		if($('#browse_genre :selected').val() == 0) {
			$('.searchAgainNoGenre').html('');
		}
		if($('#browse_venue :selected').val() == 0) {
			$('.searchAgainNoVenue').html('');
		}
		runQuickSearch();
	});
	$('.searchAgainNoPicks').click(function(event){
		event.preventDefault();
		$('#browse_picks').val('0').removeAttr('checked').attr('unchecked','unchecked');
		runQuickSearch();
	});
	$('.searchAgainNoLive').click(function(event){
		event.preventDefault();
		$('#browse_live').val('0').removeAttr('checked').attr('unchecked','unchecked');
		runQuickSearch();
	});
	$('.searchAgainNoVenue').click(function(event){
		event.preventDefault();
		$('#browse_venue option:nth(0)').attr('selected','selected');
		$('.searchAgainNoVenue').html('');
		runQuickSearch();
	});
	$('.searchAgainNoGenre').click(function(event){
		event.preventDefault();
		$('#browse_genre option:nth(0)').attr('selected','selected');
		$('.searchAgainNoGenre').html('');
		runQuickSearch();
	});
	
	// PAGINATION
	$('.browse-navFrontInactive, .browse-navPrevInactive, .browse-navNextInactive, .browse-navLastInactive').live('click', function(event){
		event.preventDefault();
		return false;
	});
	$('#paginationInput').keydown(function(event){
		if ((event.keyCode == 9) || (event.keyCode == 13)) {
			$(this).change().blur();
			runQuickSearch();
		}
	});
	$('.browse-navFront').live('click', function(event) {
		event.preventDefault();
		$('#paginationInput').val(1);
		runQuickSearch();
	});
	$('.browse-navPrev').live('click', function(event) {
		event.preventDefault();
		currentPage = $('#paginationInput').val();
		if ($('#paginationInput').val() >= 2) {
			$('#paginationInput').val(parseInt(currentPage) - 1);
		} else {
			$('#paginationInput').val('1');
		}
		runQuickSearch();
	});
	$('.browse-navNext').live('click', function(event) {
		event.preventDefault();
		currentPage = $('#paginationInput').val();
		$('#paginationInput').val(parseInt(currentPage) + 1);
		runQuickSearch();
	});
	$('.browse-navLast').live('click', function(event) {
		event.preventDefault();
		hiddenLastPage = $('#paginationLastPage').val();
		$('#paginationInput').val(hiddenLastPage);
		runQuickSearch();
	});
	
// PICKS AUTOCOMPLETE
	function log(message) {
		$("<div/>").text(message).prependTo("#log");
		$("#log").attr("scrollTop", 0);
	}
	var pickListRequest = null;
	function getPicksList() {
		if (pickListRequest) {
			pickListRequest.abort();
			pickListRequest = null;
		}
		pickListRequest = $.ajax({
			type: 'get',
			url: '/asset/getpickslist/',
			cache: false,
			dataType: 'json',
			success: function(json) {
				$('#currentPicksList').html(json.html);
			}
		});
	}
	
	$("#adminPicks").click(function(){
		$(this).val('');
	}).autocomplete({
		source: "/asset/adminpicks/",
		minLength: 2,
		select: function(event, ui){
			$.ajax({
				type: 'get',
				url: '/asset/getinfo/',
				data: 'id=' + ui.item.id,
				cache: false,
				dataType: "json",
				success: function(json){
					// var html = eval(json);
					if ((json) == null) {
						$("#pickFeatureInfo").html('Sorry, there was a problem loading the asset information');
					}
					else {
						$('#pickSuccess').hide();
						var newAssetImg = 'http://cdntranimages.stagedive.com/' + json.hash + '_489_1500_640x360-0001.jpg';
						$("#pickFeatureInfo img").attr('src', newAssetImg);
						$("#pickFeatureInfo h1").html('<a href="/asset/index/id/' + json.id + '/" target="_blank">' + json.title + ' by ' + json.bandName + '</a>');
						$('#pickFeatureInfo h3').html('Owner: <a href="/member/id/' + json.ownerId + ' target="_blank">' + json.owner + '</a>');
						$('#pickFeatureInfo h4').text('Uploaded: ' + json.date);
						$('#newadminpickId').val(json.id);
						$('#newadminpick').show();
					}
				},
				error: function(json) {
					$("#pickFeatureInfo").html('Sorry, there was a problem loading the form. Please close the form and try again or refresh the entire page.');
				}
			});
		}
	});
	$('#newadminpick').hide().click(function(event){
	 	var currentPickId = $('#newadminpickId').val();
		$.ajax({
			type: 'post',
			url: '/asset/makepick/',
			data: 'id=' + currentPickId,
			cache: false,
			dataType: 'json',
			success: function(json) {
				if (json.response == 'success') {
					$('#newadminpick').hide();
					$('#pickSuccess').show().html('Pick Successfully Added');
					$('#currentPicksList').html("<img class='center' src='/images/backgrounds/loader.gif'>");
					getPicksList();
				}
			},
			error: function(json) {
				$('#pickSuccess').show().html('Oops. There was a database error');
			}
		});
	});
	
	// Unpick
	$('.unpick').live("click",function(event) {
		$(this).css('color','gold');
		var currentAsset = $(this).attr('alt');
		var whichWay = $(this).text();
		$.ajax({
			type: 'Post',
			url: '/asset/makepick/',
			data: 'id=' + currentAsset + '&whichWay=' + whichWay,
			dataType: "json",
			async: false,
			success: function(obj){
				if (obj.whichWay == 'unpick') {
					//$('#pickId-' + obj.id).effect('transfer', { to: "#pickFeature", className: 'ui-effects-transfer' }, 500).fadeOut('fast');
					$('#pickId-' + obj.id + '> a:first').text('undo').css({color: 'green'});
					$('#pickId-' + obj.id).fadeIn('slow');
					$('#pickSuccess').hide();
				} else if(obj.whichWay == 'undo') {
					//$('#pickId-' + obj.id).effect('transfer', { to: "#pickFeature", className: 'ui-effects-transfer' }, 500).fadeOut('fast');
					$('#pickId-' + obj.id + '> a:first').text('unpick').css({color: '#4E94B7'});
					$('#pickId-' + obj.id).fadeIn('slow');
					$('#pickSuccess').hide();
				} else {
					alert('Oops. Sorry there was an error. Please contact Stagedive for assistance or try again.');
				}
			},
			error: function(){
				alert('Oops. There was an AJAX error. Please try again.');
			}
		});
	});
	$('#refreshPicks').click(function(event){
		$('#currentPicksList').html("<img class='center' src='/images/backgrounds/loader.gif'>");
		getPicksList();
	});
	
	// ADMIN REMOVAL
	$("#adminRemoveSearch").click(function(){
		$(this).val('');
		$('#adminWaiting').show().html("<img class='center' src='/images/backgrounds/loader.gif'>");
	}).blur(function(){
		$('#adminWaiting').hide();
	}).autocomplete({
		source: "/asset/adminpicks/",
		minLength: 2,
		select: function(event, ui){
			$.ajax({
				type: 'get',
				url: '/asset/getinfo/',
				data: 'id=' + ui.item.id,
				cache: false,
				dataType: "json",
				success: function(json){
					// var html = eval(json);
					if ((json) == null) {
						$("#removeVideoInfo").html('Sorry, there was a problem loading the asset information');
					}
					else {
						$('#adminRemoveSuccess').hide();
						var newAssetImg = 'http://cdntranimages.stagedive.com/' + json.hash + '_489_1500_640x360-0001.jpg';
						$("#removeVideoInfo img").attr('src', newAssetImg);
						$("#removeVideoInfo h1").html('<a href="/asset/index/id/' + json.id + '/" target="_blank">' + json.title + ' by ' + json.bandName + '</a>');
						$('#removeVideoInfo h3').html('Owner: <a href="/member/id/' + json.ownerId + ' target="_blank">' + json.owner + '</a>');
						$('#removeVideoInfo h4').text('Uploaded: ' + json.date);
						$('#adminRemoveId').val(json.id);
						$('#adminRemove').show();
						$('#adminWaiting').hide();
					}
				},
				error: function(json) {
					$("#removeVideoInfo").html('Sorry, there was a problem loading the form. Please close the form and try again or refresh the entire page.');
				}
			});
		}
	});
	
	$('#adminRemove').hide().click(function(event){
		var answer = confirm('Are you sure that you want to REMOVE this asset to make it invisible on the site?');
		if(answer == true) {
			var currentPickId = $('#adminRemoveId').val(),
				whichWay = 'remove';
			$.ajax({
				type: 'post',
				url: '/asset/makeinvisible/',
				data: 'id=' + currentPickId + '&whichWay=' + whichWay,
				cache: false,
				dataType: 'json',
				success: function(json) {
					if (json.response == 'success') {
						$('#adminRemove').hide();
						$('#adminRemoveSuccess').css('color','green').show().html('Succssfully Removed Asset.');
						$('#adminWaiting').hide();
					}
				},
				error: function(json) {
					$('#adminRemoveSuccessSuccess').show().html('Oops. There was a database error');
				}
			});
		}
	});
});

/**
 * slider.js
 */
$(document).ready(function() {
	$('.delete').click(function() {
		var answer = confirm('Are you sure you want to permanently delete this account?');
		return answer;
	});
	$(function(){
		// Tabs
		$('#tabs').tabs();
		//hover states on the static widgets
		$('#dialog_link, ul#icons li').hover(
			function() { $(this).addClass('ui-state-hover'); }, 
			function() { $(this).removeClass('ui-state-hover'); }
		);
	});
});
