// $(document).bind('reveal.facebox', function() { 
//   $('#cropbox').Jcrop({
//     onSelect: updateForm,
//     onChange: updateForm,
//     setSelect:   [ 0, 0, #{PHOTO_IMAGE_WIDTH}, #{PHOTO_IMAGE_HEIGHT} ],
//     aspectRatio: #{PHOTO_IMAGE_WIDTH}/#{PHOTO_IMAGE_HEIGHT}
//   });
// });

$(document).ready(function() {
	
	// Homepage Functions

	
	$(function(){

      $("ul.dropdown li").hover(function(){
        
          $(this).addClass("hover");
          $('ul:first',this).css('visibility', 'visible');
          $('ul.sub_menu',this).hide();
          $('ul.sub_menu',this).fadeIn('slow');
          $('ul.sub_menu2', this).hide();
          $('ul.sub_menu2', this).fadeIn('slow');

      }, function(){
          $(this).removeClass("hover");
          $('ul:first',this).css('visibility', 'hidden');
      });
  });

  $('.flash').click(function(){
   $.facebox('<div id="fbvideo"></div>');
   var so = new SWFObject('/flash/playerTrans.swf','fbvideo','640px','360px','0');
   so.addParam('allowscriptaccess','always');
   so.addParam('allowfullscreen','true');
   so.addVariable('file', $(this).attr('href'));
   so.addVariable('autostart','true');
   so.addVariable('controlbar','bottom');
   so.addVariable('repeat','none');
   so.addVariable('image',$(this).attr('rel'));
   so.addVariable('icons','false')
   so.addVariable('screencolor','none');
   so.addVariable('backcolor','FFFFFF');
   so.addVariable('screenalpha','0');
   so.addVariable('overstretch', 'true');
   so.write('fbvideo');
   return false;
  })


	$('#q').focus(function() {
		$(this).val('')
	});
	
	$('.homepage_delete_button').click(function() {
		var answer = confirm('Are you sure you wish to delete this image?');
		
		if(answer) {
			$.ajax({
				type: 'post',
				dataType: 'script',
				data: { '_method': 'delete' },
				url: $(this).attr('href'),
				success: function() {
					window.location = '/admin/homepages'
				}
			});
		}
		
		return false;
	});

  $('.searchCons a').click(function(event) {
    $('.searchCons').hide("slow");
		event.preventDefault();
		var link = $(this);
		var image = link.children().children(':first').children();
		var searchTextDiv = $(link.children().children()[1]);
		var searchText = $.trim(searchTextDiv.html());

		$('#search').attr('action', link.attr('href'));
		$('#search img').attr('src', image.attr('src'));
		$('#q').attr('value', searchText);
    return false;
	});
	
	$('.prev').click(function() {
		switchImage('prev');
	});
	
	$('.next').click(function() {
		switchImage('next');
	});
	
	var switchImage = function(direction) {
		currentIndex = parseInt($('.backgroundImage').attr('currentIndex'));

		lastIndex = backgrounds.length - 1
		
		nextImage = 0;
		
		if(direction === 'prev') {
			nextImage = currentIndex - 1;
		} else {
			nextImage = currentIndex + 1;
		}

		if (nextImage < 0) {
			nextImage = lastIndex;
		} else if (nextImage > lastIndex) {
			nextImage = 0
		}
		
		var style = 'background: url("' + backgrounds[nextImage].url + '") repeat scroll 0% 0% transparent; height: 617px; width: 960px; opacity: 0; -moz-border-radius: 15px; -webkit-border-radius: 15px;';

		$('.backgroundImage').attr('style', style).attr('currentIndex', nextImage);
		$('.homeAbout').html(backgrounds[nextImage].about_this_image);
		$('.backgroundImage').fadeTo("slow", 1);
	};
	
  $('.aboutActivate').mouseenter(
    function(){
      $(".homeAbout")
      .stop(true, true)
      .show("slow")
  });
  
  $('.aboutActivate').mouseleave(
    function(){
        $(".homeAbout")
        .stop(true, true)
        .hide("slow")
    });
	$('.curCons').click(
	  function(){
	    $('.searchCons')
	    .fadeIn("slow")
			return false;
	  });
	$('.searchCons').mouseleave(
	  function(){
	    $('.searchCons')
	    .fadeOut("slow")
	  });
	
	
	// Read more text plugin
	
  $("div.expander:eq(0)>.hidden_text").hide();
  $("div.expander:eq(0)").find('.read').click(function(){
    $(this).parent().parent().next().slideToggle("fast")
  });
  
  
  $(".more_info").hide();
  
  
  var $info_items = jQuery('.checkbox.has_info, .has_info')
  $info_items.bind('click keyup', function(){
    var $info_item = jQuery(this);
    $info_items.filter(function(index){
      return $(".hidden_text").css("display","block");
      }).not($info_item).parent().next().next().hide("slow");
    $info_item.parent().next().next().show("fast");
  });
  
	// Code for polling in Media section.
	HQChannel = {};
	HQChannel.Interactions = {
		
		handleSignupClick: function(button, div) {
			var button = $(button);
			var div = $(div);
			
			if (button.closest('form').length)
			{
				var form = $(button.closest('form'));
				var dataString = form.serialize();

				$.ajax({
					url: form.attr('action') + '.json',
					data: dataString,
					type: "POST",
					dataType: 'json',
					success: function(data) {
						if (data.html)
							div.html(data.html);
						else
						{
							$.each(data.errors, function(index, value) {
								var element = '#card_signup_' + value[0];
								$(element).next('.error_message').html(value[1]);
							});
						}
					}
				});
			}
			else
			{
				$.ajax({
					url: button.attr('href'),
					dataType: 'json',
					success: function(data) {
						div.html(data.html);
					}
				});
			}
		},
		
		setupSuggestCategoryButton: function(button) {
			var button = $(button);
			var category = button.prev().val();
			if (category)
			{
				var dataString = { 'category': category };
				$.ajax({
					type: "POST",
					url: button.attr('href'),
					data: dataString,
					complete: function(xhr, string) {
						button.prev().val('');
					}
				});
			}
		},
		
		setupCheckAllButtonsME: function(checkBox) {
			checkBox = $(checkBox);
			checkBoxClass = '.' + checkBox.val();
			checkBoxesToCheck = $(checkBoxClass);
			
			if(checkBox.attr('checked'))
				$.each(checkBoxesToCheck, function() {
					$(this).attr('checked', true);
				});
			else
				$.each(checkBoxesToCheck, function() {
					$(this).attr('checked', false);
				});
		}
	};
	
	$('.card_signup_button').live('click', function() {
		HQChannel.Interactions.handleSignupClick(this, '#card_signup_update_area');
		return false;
	});
	
	$('#suggest_category_button').live('click', function() {
		HQChannel.Interactions.setupSuggestCategoryButton(this);
		return false;
	});
	
	$('.check_all_me').live('click', function() {
		HQChannel.Interactions.setupCheckAllButtonsME(this);
	});
	
	$.extend({
		MediaPoller: {
			setupMediaIndexPoller: function() {
				$.PeriodicalUpdater(window.location.pathname, {
		        method: 'get',          
			      data: '', 		          
			      minTimeout: 20000,       
			      maxTimeout: 60000,       
			      multiplier: 2,          
			      type: 'json',           
		        maxCalls: 0,            
		        autoStop: 0             
		    }, function(data) {
			      $('#media_index').html(data.html);
		    });
			},
			setupGalleryIndexPoller: function(organization, gallery) {
				url = '/organizations/' + organization + '/media/galleries/' + gallery + '.json'
				updater = $.PeriodicalUpdater(url, {
		        method: 'get',          
			      data: '', 		          
			      minTimeout: 20000,       
			      maxTimeout: 60000,       
			      multiplier: 2,          			         
		        maxCalls: 0,
						type: 'html',
		        autoStop: 0             
		    }, function(data) {
			      $('#media_header').html(data);
		    });
			}
		}
	});

	if ($('#media_index').length)
	{
		$.MediaPoller.setupMediaIndexPoller();
	}	

	$('.card_batch_edit_link').click(function() {
		var url = $(this).attr('href');
		var div = $(this).closest('.signup');
		$.ajax({
			url: url, 
			dataType: 'json',
			type: 'GET',
			success: function(data){
				div.next().html(data.html).show();
			}
		});
		return false;
	}); 
	
	$('.delete_admin_button').live('click', function() {
		var button = $(this);
		var form = button.closest('form');
		var url = form.attr('action');
		var dataString = form.serialize();
		
		var answer = confirm("Delete this signup?");
		if (answer) {
			$.ajax({
				type: "DELETE",
				data: dataString,
				url: url,
				success: function() {
					button.closest('.signup_info').hide();
					button.closest('.signup_info').prev().hide();
				}
			});
		}
		return false;
	});

	$('.orgs_deals_admin_save').live('click', function() {
		var button = $(this);
		var form = button.closest('form');
		var dataString = form.serialize();
		$.ajax({
			url: form.attr('action') + '.json',
			dataType: 'json',
			type: 'POST',
			async: false,
			data: dataString,
			success: function(data) {
			}
		});
		//return false;
	});
	
	$('.signup_admin_save').live('click', function() {
		var button = $(this);
		var form = button.closest('form');
		var dataString = form.serialize();
		
		$.ajax({
			url: form.attr('action') + '.json',
			dataType: 'json',
			type: 'POST',
			data: dataString,
			success: function(data) {
				button.closest('.signup_info').hide();
				$('#card_signup_submit').closest('.signup_info').prev().children('.printing_status').html(data.html);
			}
		});
		
		return false;
	});
	
	$("#secretMouse").mouseenter(function(){
	  $('#secretProgrammers')
	  .stop(true, true)
	  .fadeIn("slow")
	});
	$("#secretMouse").mouseleave(function(){
	  $('#secretProgrammers')
	  .stop(true, true)
	  .fadeOut("slow")
	})
	
	$('.search_result:last, .deal_summary:last, .calendar_summary:last').attr('style', 'border-bottom:none;');

  $('#myHQpage_viewer').mouseenter(function(){
    $('#media_controls')
    .stop(true, true)
    .fadeIn("slow")
  });
  $('#myHQpage_viewer').mouseleave(function(){
    $('#media_controls')
    .stop(true, true)
    .fadeOut("slow")
  });
  
		$(".edit_admin_photo_link").live("click", function(){
			$.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
			return false;
		});
		
		$('.admin_remove_crop').click(function() {
			$.get(this.href, '', '', 'script');
			return false;
		});
		
		$('.facebox_window').click(function(){
      		$.get(this.href, '', '', 'script');
      		return false;
    	});
		
			$('#suggestions_submit').click(function(){
      	form = $(this).closest('form');
			  
        if ( ($('#invitation_0_name').val() == "") && ($('#invitation_1_name').val() == "") )
        {	
					alert('You must refer at least 2 reputable organizations to send your feedback')
					return false;
				}
				else
				{
					$(this).attr('disabled', 'disabled').val('Sending...');
					form.submit();
				}
				return false;
			});
        
        $('#invitation_link').unbind('click.dirty_form');
    
        $('#invitation_link').click(function() {
            if (($('#suggestions .form:hidden').length - 1) == 0)
                $('#invitation_link').hide();
            $('#suggestions :hidden:first').slideDown('slow');
            return false;
        });

        /*$('.search_form_right .button').click(function() {
          dataString = 'q=' + $('.search_form_right #q').val();
          $.get($(this).attr('action'), dataString, null, "script");
          return false;
        });*/
        
        $("#calendar_slider").easySlider({
          "controlsBefore": '<div class="calWidget_nav">',
          "controlsAfter": '</div>',
          "prevText": '',
          "nextText": '',
          "auto": true,
          "continuous": true,
          "speed": 500,
          "pause": 6000
        });
        
        
        $("#changeSortCal").click(function(){
            $("#search_choose_cal").hide();
            $(".calendarContainer").slideDown('slow');
            $(this).html("");
        });
        $(".calendar-close-button").click(function(){
            $(".calendarContainer").hide();
            $("#search_choose_cal").slideDown('slow');
            $("#changeSortCal").html("Show Calendar");
        });

		$(".deal_close").click(function(){
			$("#deal_notice").fadeOut();
			$(".deal_notice_shadow").fadeOut();
		});

	//general functions
	$(".live").live("click", function() {
		$.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
		return false;
	});

    $(".turn-me-into-a-date-picker").datepicker({
        onSelect: function(dateText, inst) {
          dataString = "current_date=" + dateText;
          $.get('/calendars', dataString, null, "script");
          //var url = "http://invent.hqchannel.com/calendars?current_date=" + dateText;
          //window.location.href = url;
        }
    });
	
	$("#organization_name").change(function() {
		$.post("/organizations/live_validation", { name: $(this).val() }, null, "script");
	});
	$("#organization_hq_url").change(function() {
		$.post("/organizations/live_validation", { hq_url: $(this).val() }, null, "script");
	});
	
	$(".vote_link").live("click", function (){
		$.ajax({type: "GET", url: $(this).attr("href"), dataType: "script"});
		return false;
	});
	
	$(".search_result").live("mouseover", function(){
		$("#search_image_banner").attr("src", $(this).find(".search_image_banner").attr("src"));
	});
	
	$(".deal_summary").live("mouseover", function(){
		$("#search_image_banner").attr("src", $(this).find(".search_image_banner").attr("src"));
	});

    $(".calendar_summary").live("mouseover", function() {
        $("#search_image_banner").attr("src", $(this).find(".search_image_banner").attr("src"));
    })
	
	$(".need_login").easyTooltip({
		useElement: "need_login",
		tooltipId: "need_login_tt"
	});
	$("#need_login_close").live("click", function(){
		$("#need_login_tt").hide();
		return false;
	});
	
	/*$('.already_have_tooltip').easyTooltip({
		useElement: "already_have_tooltip",
		tooltipID: "already_have_tooltip_tt"
	});
	
	$("#already_have_tooltip_close").live("click", function() {
		$("#easyTooltip").hide();
		return false;
	});*/
	
	$(".dropdown_menu1").hover(
		function(){
			$(this).children("ul").show();
			$("#logo_small").css('zIndex', -1);
		},
		function(){
			$(this).children("ul").hide();
			$("#logo_small").css('zIndex', 1)
		}
	);
	$(".drop_down1").hover(
		function(){
			$(this).parent().show();
			$("#logo_small").css('zIndex', -1)
		}
	);
	
	$("#request_invitation_link").click(function (){
		$("#request_invitation").show();
		$("#subscription_info").hide();
		return false;
	});
	
	//This is the drop down menu
		
  $(".drop_down").mouseenter(
    function () {
      $(".drop_down_menu")
      .stop(true, true)
      .show( 'slide', {direction: 'up'});
    });
  $("#tabbed_nav").mouseleave(
    function () {
      $(".drop_down_menu")
      .stop(true, true)
      .hide( 'slide', {direction: 'up'});
    });
    
	
	$('textarea[maxlength]').keyup(function(){  
			//get the limit from maxlength attribute  
			var limit = parseInt($(this).attr('maxlength'));  
			//get the current text inside the textarea  
			var text = $(this).val();  
			//count the number of characters in the text  
			var chars = text.length;  
			
			//check if there are more characters then allowed  
			if(chars > limit){  
				//and if there are use substr to get the text before the limit  
				var new_text = text.substr(0, limit);  
				//and change the current text with the new text  
				$(this).val(new_text);  
			}  
		});

	$(".show_event").live("click", function(){
		$('.long_description').hide();
		$('.short_description').show();
		$(this).parent().prev().parent().parent().hide();
		$(this).parent().parent().parent().next().slideDown();
		return false;
	});
	
});



// Always send the authenticity_token with ajax
$(document).ajaxSend(function(event, request, settings) {
    if ( settings.type != 'GET' ) {
        settings.data = (settings.data ? settings.data + "&" : "")
            + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );
    }
});

//This is the lavaLamp

(function(jQuery) {
jQuery.fn.lavaLamp = function(o) {
	o = jQuery.extend({
				target: 'li', 
				fx: 'swing',
				speed: 500, 
				click: function(){return true}, 
				startItem: '',
				autoReturn: true,
				returnDelay: 0,
				setOnClick: true,
				homeTop:0,
				homeLeft:0,
				homeWidth:0,
				homeHeight:0,
				returnHome:false,
				autoResize:false
				}, 
			o || {});

	// parseInt for easy mathing
	function getInt(arg) {
		var myint = parseInt(arg);
		return (isNaN(myint)? 0: myint);
	}

	if (o.autoResize)
		jQuery(window).resize(function(){
			jQuery(o.target+'.selectedLava').trigger('mouseenter');
		});

	return this.each(function() {
		// ensures parent UL or OL element has some positioning
		if (jQuery(this).css('position')=='static')
			jQuery(this).css('position','relative');

		// create homeLava element if origin dimensions set
		if (o.homeTop || o.homeLeft) { 
			var $home = jQuery('<'+o.target+' class="homeLava"></'+o.target+'>').css({ left:o.homeLeft, top:o.homeTop, width:o.homeWidth, height:o.homeHeight, position:'absolute' });
			jQuery(this).prepend($home);
		}

		var path = location.pathname + location.search + location.hash, $selected, $back, $lt = jQuery(o.target+'[class!=noLava]', this), delayTimer, bx=0, by=0;

		// start $selected default with CSS class 'selectedLava'
		$selected = jQuery(o.target+'.selectedLava', this);
		
		// override $selected if startItem is set
		if (o.startItem != '')
			$selected = $lt.eq(o.startItem);

		// default to $home element
		if ((o.homeTop || o.homeLeft) && $selected.length<1)
			$selected = $home;

		// loop through all the target element a href tags and
		// the longest href to match the location path is deemed the most 
		// accurate and selected as default
		if ($selected.length<1) {
			var pathmatch_len=0, $pathel;
	
			$lt.each(function(){ 
				var thishref = $('a:first',this).attr('href');
				//console.log(thishref+' size:'+thishref.length);
				if (path.indexOf(thishref)>-1 && thishref.length > pathmatch_len )
				{
					$pathel = $(this);
					pathmatch_len = thishref.length;
				}
	
			});
			if (pathmatch_len>0) {
				//console.log('found match:'+$('a:first',$pathel).attr('href'));
				$selected = $pathel;
			}
			//else 
				//console.log('no match!');
		}
	
		// if still no matches, default to the first element
		if ( $selected.length<1 )
			$selected = $lt.eq(0);

		// make sure we only have one element as $selected and apply selectedLava class
		$selected = jQuery($selected.eq(0).addClass('selectedLava'));
			
		// add mouseover event for every sub element
		$lt.bind('mouseenter', function() {
			//console.log('mouseenter');
			// help backLava behave if returnDelay is set
			if(delayTimer) {clearTimeout(delayTimer);delayTimer=null;}
			move(jQuery(this));
		}).click(function(e) {
			if (o.setOnClick) {
				$selected.removeClass('selectedLava');
				$selected = jQuery(this).addClass('selectedLava');
			}
			return o.click.apply(this, [e, this]);
		});
		
		// creates and adds to the container a backLava element with absolute positioning
		$back = jQuery('<li class="backLava"><div class="leftLava"></div><div class="bottomLava"></div><div class="cornerLava"></div></li>').css('position','absolute').prependTo(this);

		// setting css height and width actually sets the innerHeight and innerWidth, so
		// compute border and padding differences on styled backLava element to fit them in also.
		bx = getInt($back.css('borderLeftWidth'))+getInt($back.css('borderRightWidth'))+getInt($back.css('paddingLeft'))+getInt($back.css('paddingRight'));
		by = getInt($back.css('borderTopWidth'))+getInt($back.css('borderBottomWidth'))+getInt($back.css('paddingTop'))+getInt($back.css('paddingBottom'));

		// set the starting position for the lavalamp hover element: .back
		if (o.homeTop || o.homeLeft)
			$back.css({ left:o.homeLeft, top:o.homeTop, width:o.homeWidth, height:o.homeHeight });
		else
		{
			$back.css({ left: $selected.position().left, top: $selected.position().top, width: $selected.outerWidth()-bx, height: $selected.outerHeight()-by }); 
		}

		// after we leave the container element, move back to default/last clicked element
		jQuery(this).bind('mouseleave', function() {
			//console.log('mouseleave');
			var $returnEl = null;
			if (o.returnHome)
				$returnEl = $home;
			else if (!o.autoReturn)
				return true;
		
			if (o.returnDelay) {
				if(delayTimer) clearTimeout(delayTimer);
				delayTimer = setTimeout(function(){move($returnEl);},o.returnDelay);
			}
			else {
				move($returnEl);
			}
			return true;
		});

		function move($el) {
			if (!$el) $el = $selected;

			$back.stop()
			.animate({
				left: $el.position().left,
				top: $el.position().top,
				width: $el.outerWidth()-bx,
				height: $el.outerHeight()-by
			}, o.speed, o.fx);
		};
	});
	
};
})(jQuery);


//End of LavaLamp
