var fishhound_util = fishhound_util || {};
(function ($) {

  fishhound_util.premium = function(url, dest) {
    // if clicking 'My Fishhound' link, send user to dashboard based on role.
    if(dest == '=/my-fishhound') {
      $('.modal-premium #user-login-form').attr('action', '/node?destination=login/redirect');
    }
    // if logging in via modal from elsewhere, send user to page.
    else {
      $('.modal-premium #user-login-form').attr('action', url + '?destination' + dest.replace('=/', '='));
    }
    $('.modal-premium').dialog('open');
  };

//watersmap default to us
window.onload = function() {
	$('#edit-drilldown-country').val('qm');
	//$('#statedrilldown-state-replace .form-item-drilldown-province select').reset();
	$('#statedrilldown-state-replace .form-item-drilldown-province select').val("");
} 

  Drupal.behaviors.fishhound = {
    attach: function(context) {
    			
      // Do not run when using IMCE file browser.
      var body = $('body').attr('class');
      if(body != 'imce') {

        // Display on load if radio is set to Yes.
        if($("input[name='field_user_sms_alerts[und]']:checked").val() == 0) {
          $('#edit-field-user-mobile-number').hide();
        }
        // Show/hide based on Yes/No change.
        var smsn = "input[name='field_user_sms_alerts[und]']";
        $(smsn).change(function() {
          if($(this).val() == 1) {
            $('#edit-field-user-mobile-number').show('fast');
          }
          else {
            $('#edit-field-user-mobile-number').hide('fast');
          }
        });

        // Display on load if radio is set to Yes.
        if($("input[name='field_user_reffered_by_pro[und]']:checked").val() == 0) {
          $('#edit-field-user-pro-referrer').hide();
        }
        // Show/hide based on Yes/No change.
        var smsn = "input[name='field_user_reffered_by_pro[und]']";
        $(smsn).change(function() {
          if($(this).val() == 1) {
            $('#edit-field-user-pro-referrer').show('fast');
          }
          else {
            $('#edit-field-user-pro-referrer').hide('fast');
          }
        });

		 //sign up button toslect appropriate radio button and submit form 
       $('.sign-up-mem-button-premium img').live( 'click', function(e) {
			 		$('input.one-year-20-radio').attr('checked', true);
					$('body.page-registration #premium-membership-type-form form').submit();
					$('body.page-upgrade-premium #premium-membership-type-form form').submit();
			 });
			 
			 $('.sign-up-mem-button-free img').live( 'click', function(e) {
			 		$('input.free-radio').attr('checked', true);
			 		$('input.one-year-radio').attr('checked', false);
			 		$('body.page-registration #premium-membership-type-form form').submit();
			 });
		
		//step 2 for user mem reg next button
		/* moved to fh_user_register.js.
		 $('.step2-next-button img').live( 'click', function(e) {
			 		$('#edit-continue').click();
			 });*/


		/*
		*photo and video expander for water media
		*/
		//photo
		$('#photo-expander').live( 'click', function(e) {
			var size = $('.view-water-media.view-display-id-default div.view-content div.item-list').children('.hide-photo').size();

			$('.view-water-media.view-display-id-default div.view-content div.item-list').children('.hide-photo').each(function(index,el) {
    			$(el).slideDown('slow');
    			$(el).removeClass('hide-photo');
    			return false;
    		});

    	 	if(size == 1){
    			$('div.expand-button-photo').hide();
    		}
		});
		//video
		$('#video-expander').live( 'click', function(e) {
			var size = $('.view-water-media.view-display-id-videos div.view-content div.item-list').children('.hide-video').size();

			$('.view-water-media.view-display-id-videos div.view-content div.item-list').children('.hide-video').each(function(index,el) {
    			$(el).slideDown('slow');
    			$(el).removeClass('hide-video');
    			return false;
    		});

    	 	if(size == 1){
    			$('div.expand-button-video').hide();
    		}
		});

	  	/*
		*FLY PAGER FOR HATCH ALERTS USER DASH
		*/
		//for the previous button
		$('.fly-previous').live( 'click', function(e) {
 			//number of flies
 			var randID = $(this).attr('id');
 			var numChildren = $('.numflies.'+randID).val();
 			//looping through all the fly wrapper divs. checking which one is not hidden and hiding it and showing the next
 			//if last child show first
 			$('.fly-current-hatches-wrapper.'+randID).children('.fly-pager-item').each(function(i,e) {

    			if(!$(e).hasClass('current-hatch-fly-hide') && (i-1) >= 0){

    				$(e).addClass('current-hatch-fly-hide');

    				$('.fly-current-hatches-wrapper.'+randID).children('.fly-pager-item').each(function(index,el) {
    					if(index == (i-1)){

							$(el).removeClass('current-hatch-fly-hide');
    						return false;

    					}

    				});

    				return false;

    			}
    			else if(!$(e).hasClass('current-hatch-fly-hide') && (i-1) < numChildren){

    				$(e).addClass('current-hatch-fly-hide');

    				$('.fly-current-hatches-wrapper.'+randID).children('.fly-pager-item').each(function(index,el) {
    					if(index == (numChildren-1)){

							$(el).removeClass('current-hatch-fly-hide');
    						return false;

    					}

    				});

    				return false;

    			}
    		});
		});
		//for the next button
		$('.fly-next').live( 'click', function(e) {

			var randID = $(this).attr('id');
 			var numChildren = $('.numflies.'+randID).val();

			$('.fly-current-hatches-wrapper.'+randID).children('.fly-pager-item').each(function(i,e) {
    		console.log(i);
    			if(!$(e).hasClass('current-hatch-fly-hide') && (i+1) <= (numChildren-1)){

    				$(e).addClass('current-hatch-fly-hide');
	    			$('.fly-current-hatches-wrapper.'+randID).children('.fly-pager-item').each(function(index,el) {
    					if(index == (i+1)){

							$(el).removeClass('current-hatch-fly-hide');
    						return false;

    					}

    				});
    				return false;

    			}
    			else if(!$(e).hasClass('current-hatch-fly-hide') && (i+1) > (numChildren-1)){

	    			$(e).addClass('current-hatch-fly-hide');
    				$('.fly-current-hatches-wrapper.'+randID).children('.fly-pager-item').each(function(index,el) {
    					if(index == 0){

							$(el).removeClass('current-hatch-fly-hide');
    						return false;

    					}

    				});
    				return false;

    			}
			});
		});
/////////END FLY PAGER
				if ($('#edit-field-user-mailing-address-copybiz').attr('checked')) {
         	 $('#edit-field-user-mailing-address').hide('fast');
				}
       // Mailing Address is same as Business Address
       $('#edit-field-user-mailing-address-copybiz').change(function(){
         if ($('#edit-field-user-mailing-address-copybiz').attr('checked')) {
         	 $('#edit-field-user-mailing-address').hide('slow');
         }
         else {
         		$('#edit-field-user-mailing-address').show('slow');
         }
       });
       

       // Open embedded video when thumbnail clicked
       $('.ajaxified-video a').click(function(e) {
         e.preventDefault();
         var url = $(this).attr('href');
         $(this).parent().hide(700, function(e) { 
           $(this).html('<iframe allowfullscreen="" frameborder="0" height="345" src="' + url +'?autoplay=1" width="560"></iframe>').show(700);
         });
       });

        /*
         * login showing/hiding functionality
         */
        $('#block-user-login').hide();
        $(document).click(function(e) {
          //hide login form when user clicks elsewhere on page
          if($('#block-user-login').hasClass('visible')
              && !$(e.target).parents().is('#block-user-login')
              && !$(e.target).is('#block-user-login')) {
            $('#block-user-login').hide('slow', function() {
              $(this).removeClass('visible');
            });
          }
          // hide all form selects when user clicks elsewhere on page
          if(!($(e.target).closest('.jquery_dropdown_container').is('div.jquery_dropdown_container'))) {
            $('.open-menu').attr('style', 'display:hidden').removeClass('open-menu');
          }
        });
        $('#user-login-link').click(function(e) {
          $('#block-user-login').show('slow', function() {
            $(this).addClass('visible');
          });
          e.preventDefault();
        });
        $('#edit-panes-fh-user-register-account-referral-0')
          .bind('click', function(){
            $('#checkout-referrer')
            .show('fast');
          });
        $('#edit-panes-fh-user-register-profile-sms-alerts-0')
          .bind('click', function(){
            $('#mobile-alerts')
            .show('fast');
          });

        // Premium modal login
        $('.modal-premium').dialog({
          width: 715,
          title: 'My Fishhound Login',
          autoOpen: false,
          modal: true,
          stack: false
        });

        // add any links that should open premium modal here.  Make sure to include body.not-logged-in and/or body.guest
        // removed per request: body.guest a[href*="add-fav-water"]
        $('body.not-logged-in a[href*="/section/"], body.guest a[href*="/section/"], body.not-logged-in .node a.premium[href*="/user/login"], body.guest .node a[href*="/user/login"], body.not-logged-in a[href*="add-fav-water"]')
          .live( 'click', function(e) {
            e.preventDefault();
            var url = window.location.pathname;
            // Add equal sign to var so replace() removes only the first slash in path causing ugly urls (i.e. fishhound.com//discounts-and-promotions)
            var dest = '=' + $(this).attr('href');
            fishhound_util.premium(url, dest);
          });

        // Freemium (Guest) modal login
        /*$('.modal-freemium').dialog({
          width: 715,
          title: 'My Fishhound Login',
          autoOpen: false,
          modal: true,
          stack: false
        });*/
        
        //Freemium (Guest) water modal login
        $('.water-freemium').dialog({
          width: 731,
          height:478,
          title: 'My Fishhound Login',
          autoOpen: false,
          modal: true,
          stack: false
        });
        
        // Generic Freemium (Guest) modal login
        $('#fh-generic-freemium-modal').dialog({
          width: 620,
          height:400,
          modal: true,
          stack: false,
          autoOpen:false
        });
        
        $('#fh-product-freemium-modal').dialog({
          width: 620,
          height:400,
          modal: true,
          stack: false,
          autoOpen:false
        });
        
        // Add any links that should open Freemium (Guest) login modal.
        // 'Add Photo', 'Add Video' on Water, respective Resources pages.
        $('body.not-logged-in .node a.guest[href*="/user/login"], body.not-logged-in a[href*="my-fishhound"], body.not-logged-in a[href*="/node/add"], body.not-logged-in a[href*="/add/photo"], .comment-add-not-logged-in, body.not-logged-in .comment-reply, body.not-logged-in a[href*="discounts-and-promotions"], body.not-logged-in a[href*="add-fav-water"], body.not-logged-in a[href*="/user-water-update/"], body.not-logged-in a[href*="add-photo"], body.not-logged-in a[href*="add-video"]')
          .live('click', function(e) {
            e.preventDefault();

            var url = window.location.pathname;
            
            if($(this).text() == "My Fishhound"){ window.location.href = '/community';}
            else{ $('#fh-generic-freemium-modal').dialog('open');}
          });
        $('.trigger-product-freemium-modal')
          .live('click', function(e) {
            e.preventDefault();
            $('#fh-product-freemium-modal').dialog('open');
          });
        
             
        
        jQuery(".expanded[href='/flyfishing']:contains('Fishing')").not(":contains('Fly')").removeAttr('href');
             
        
        
        
        $('body.not-logged-in a[href*="resources/recipes/upload"]')
          .live('click', function(e) {
            e.preventDefault();
            $('#recipe-modal').dialog({
              width: 550,
              height:400,
              modal: true,
              stack: false
            });
          });
        
        // Anonymous search-for-the-best modal
        $('.modal-sftb-anon').dialog({
          width: 658,
          title: 'My Fishhound Login',
          autoOpen: false,
          modal: true,
          stack: false
        });

        // Add any links that should open anonymous search-for-the-best modal
        $('body.not-logged-in .search-for-the-best-zip-search-form')
          .live('click', function(e) {
            e.preventDefault();
            var url = window.location.pathname;
            // Add equal sign to var so replace() removes only the first slash in path causing ugly urls (i.e. fishhound.com//discounts-and-promotions)
            var dest = '=' + $(this).attr('href');
            $('.modal-sftb-anon').dialog('open');
          });
        
        // Freemium search-for-the-best modal
        $('.modal-sftb-free').dialog({
          width: 338,
          title: 'Premium Feature',
          autoOpen: false,
          modal: true,
          stack: false
        });

        // Add any links that should open freemium search-for-the-best modal
        /*$('body.guest .search-for-the-best-zip-search-form')
          .live('click', function(e) {
            e.preventDefault();
            var url = window.location.pathname;
            // Add equal sign to var so replace() removes only the first slash in path causing ugly urls (i.e. fishhound.com//discounts-and-promotions)
            var dest = '=' + $(this).attr('href');
            $('.modal-sftb-free').dialog('open');
          });*/
        
        // "Request updated report" modal for anonymous users
        $('.modal-updated-report').dialog({
          width: 698,
          title: 'My Fishhound Login',
          autoOpen: false,
          modal: true,
          stack: false
        });

        // Show 'Additional Flies' fields on 'Add new Fly' click.
        $("a.form-add-fly").click(function() {
          $("#edit-field-catch-more-flies").show('200');
          $("#edit-field-hatch-alert-more-flies").show('200');
          $("#edit-field-migration-alert-more-flies").show('200');
          $("#edit-field-section-more-flies").show('200');
          $("#edit-field-section-update-more-flies").show('200');
          $("#edit-field-water-more-flies").show('200');
          return false;
        });

		// Premium Membership preview screenshots modal
		var membershipScreenshots=new Array();
		membershipScreenshots[0]=".screenshot-reports";
		membershipScreenshots[1]=".screenshot-water-stats";
		membershipScreenshots[2]=".screenshot-fish-species";
		membershipScreenshots[3]=".screenshot-flies";
		membershipScreenshots[4]=".screenshot-free-apps";
		membershipScreenshots[5]=".screenshot-premium-apps";
		membershipScreenshots[6]=".screenshot-water-search";
		membershipScreenshots[7]=".screenshot-personal-dash";
		membershipScreenshots[8]=".screenshot-water-sections";
		membershipScreenshots[9]=".screenshot-hatch-alerts";
		membershipScreenshots[10]=".screenshot-active-flies";
		membershipScreenshots[11]=".screenshot-fish-caught";
		membershipScreenshots[12]=".screenshot-premium-discounts";

		$.each(membershipScreenshots, function(key, value){
			$(value).dialog({
			  width: 517,
			  //height: auto,
			  modal: true,
			  resizable: false,
			  autoOpen: false,
			  zIndex: 9999999,
			  closeOnEscape: true,
			  draggable: false
			});
		});

		
		
		$('.premium-membership-screenshot').click(function() {
			$('.'+ $(this).attr('rel')).dialog("open");
			return false;
		});
		
		 //modal frame for fish caught tab in water page
		 $('.caught-trigger').live('click', function(e) {  $('#caught-photo-modal-wrapper').html( $('.caught-photo-modal', $(this).parent().parent()).html())
             $('#caught-photo-modal-wrapper').dialog('open');
		 });
		$('#caught-photo-modal-wrapper').each(function(key, value){
			$(value).dialog({
			  width: 730,
			  //height: auto,
			  modal: true,
			  resizable: false,
			  autoOpen: false,
			  zIndex: 9999999,
			  closeOnEscape: true,
			  draggable: false
			});
		});
		//end modal fish caught tab in water page
		
		$('a.free-membership-modal-feature').click(function() {
			$('.'+ $(this).attr('rel')).dialog("open");
			return false;
		});
    $('body.node-type-water .fav-waters a.fav-waters-btn').click(function(e){
      e.preventDefault();
      var empty = $('body.node-type-water .view-water-my-waters-sidebar .view-content .views-row .views-field .field-content').html();
      if(empty == ''){
      	$('body.node-type-water .view-water-my-waters-sidebar .view-content .views-row .views-field .field-content').html('<p>There are no waters on your dashboard.</p>');
      }
      $('body.node-type-water .view-water-my-waters-sidebar').toggleClass('active');
      e.stopPropagation();
    });
		$('body.node-type-water').click(function(e){
			if($('body.node-type-water .view-water-my-waters-sidebar').hasClass('active')){
				$('body.node-type-water .view-water-my-waters-sidebar').removeClass('active');
			}
		});
    
    $('#edit-field-water-update-w-flow-na-und').click(function(e){
      if($(this).attr("checked")){
        $('.field-name-field-water-update-w-flow-r .fivestar-widget').hide();
        $('.w-flow-no-rating').show();
        $('#edit-field-water-update-w-flow-und-0-value').attr("disabled", "disabled");
        $('#edit-field-water-update-w-flow-g-und').attr("disabled", "disabled");
      }else{
        $('.field-name-field-water-update-w-flow-r .fivestar-widget').show();
        $('.w-flow-no-rating').hide();
        $('#edit-field-water-update-w-flow-und-0-value').removeAttr("disabled");
        $('#edit-field-water-update-w-flow-g-und').removeAttr("disabled");
      }
    });
      }
      $('a.fish-species-tab').click(function(e){
        e.preventDefault();
        if(!$(this).hasClass('active')){
          $('.fish-species-tab').removeClass('active');
          $(this).addClass('active')
          var contentId = $(this).attr('href');
          $('.fish-species-tab-content').hide();
          $('#' + contentId).show();
        }
      });

      // Show all magazine covers.
      $('.view-magazine-issues .more-link a').click(function(e) {
        e.preventDefault();
        $('.issues .all-issues').show(500);
        $(this).parent().hide();
      });

      // Open magazine links in new tab.
      $('.views-field-field-magazine-issue-date a, .views-field-field-magazine-issue-cover a, a.mag-subscribe').click(function() {
        this.target = "_blank";
      });

    }
  };
  
  

})(jQuery);
;
(function($) {

  $.fn.tweet = function(o){
    var s = $.extend({
      username: null,                           // [string or array] required unless using the 'query' option; one or more twitter screen names
      list: null,                               // [string]   optional name of list belonging to username
      favorites: false,                         // [boolean]  display the user's favorites instead of his tweets
      query: null,                              // [string]   optional search query
      avatar_size: null,                        // [integer]  height and width of avatar if displayed (48px max)
      count: 3,                                 // [integer]  how many tweets to display?
      fetch: null,                              // [integer]  how many tweets to fetch via the API (set this higher than 'count' if using the 'filter' option)
      retweets: true,                           // [boolean]  whether to fetch (official) retweets (not supported in all display modes)
      intro_text: null,                         // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                         // [string]   do you want text AFTER your tweets?
      join_text:  null,                         // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",        // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                   // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "i am",               // [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",     // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at",   // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                       // [string]   optional loading text, displayed while tweets load
      refresh_interval: null ,                  // [integer]  optional number of seconds after which to reload tweets
      twitter_url: "twitter.com",               // [string]   custom twitter url, if any (apigee, etc.)
      twitter_api_url: "api.twitter.com",       // [string]   custom twitter api url, if any (apigee, etc.)
      twitter_search_url: "search.twitter.com", // [string]   custom twitter search url, if any (apigee, etc.)
      template: "{avatar}{time}{join}{text}",   // [string or function] template used to construct each tweet <li> - see code for available vars
      comparator: function(tweet1, tweet2) {    // [function] comparator used to sort tweets (see Array.sort)
        return tweet2["tweet_time"] - tweet1["tweet_time"];
      },
      filter: function(tweet) {                 // [function] whether or not to include a particular tweet (be sure to also set 'fetch')
        return true;
      }
    }, o);

    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        // See http://daringfireball.net/2010/07/improved_regex_for_matching_urls
        var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;
        this.each(function() {
          returning.push(this.replace(regexp,
                                      function(match) {
                                        var url = (/^[a-z]+:/i).test(match) ? match : "http://"+match;
                                        return "<a href=\""+url+"\">"+match+"</a>";
                                      }));
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+(\w+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"@<a href=\"http://"+s.twitter_url+"/$1\">$1</a>"));
        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        // Support various latin1 (\u00**) and arabic (\u06**) alphanumeric chars
        var regexp = /(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi;
        var usercond = (s.username && s.username.length == 1) ? '&from='+s.username.join("%2BOR%2B") : '';
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://'+s.twitter_search_url+'/search?q=&tag=$1&lang=all'+usercond+'">#$1</a>'));
        });
        return $(returning);
      },
      capAwesome: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/\b(awesome)\b/gi, '<span class="awesome">$1</span>'));
        });
        return $(returning);
      },
      capEpic: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/\b(epic)\b/gi, '<span class="epic">$1</span>'));
        });
        return $(returning);
      },
      makeHeart: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(&lt;)+[3]/gi, "<tt class='heart'>&#x2665;</tt>"));
        });
        return $(returning);
      }
    });

    function parse_date(date_str) {
      // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
      // cannot handle in IE. We therefore perform the following transformation:
      // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    }

    function relative_time(date) {
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - date) / 1000, 10);
      var r = '';
      if (delta < 60) {
        r = delta + ' seconds ago';
      } else if(delta < 120) {
        r = 'a minute ago';
      } else if(delta < (45*60)) {
        r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
      } else if(delta < (2*60*60)) {
        r = 'an hour ago';
      } else if(delta < (24*60*60)) {
        r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
        r = 'a day ago';
      } else {
        r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
      }
      return 'about ' + r;
    }

    function build_url() {
      var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
      var count = (s.fetch === null) ? s.count : s.fetch;
      if (s.list) {
        return proto+"//"+s.twitter_api_url+"/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+count+"&callback=?";
      } else if (s.favorites) {
        return proto+"//"+s.twitter_api_url+"/favorites/"+s.username[0]+".json?count="+s.count+"&callback=?";
      } else if (s.query === null && s.username.length == 1) {
        return proto+'//'+s.twitter_api_url+'/1/statuses/user_timeline.json?screen_name='+s.username[0]+'&count='+count+(s.retweets ? '&include_rts=1' : '')+'&callback=?';
      } else {
        var query = (s.query || 'from:'+s.username.join(' OR from:'));
        return proto+'//'+s.twitter_search_url+'/search.json?&q='+encodeURIComponent(query)+'&rpp='+count+'&callback=?';
      }
    }

    return this.each(function(i, widget){
      var list = $('<ul class="tweet_list">').appendTo(widget);
      var intro = '<p class="tweet_intro">'+s.intro_text+'</p>';
      var outro = '<p class="tweet_outro">'+s.outro_text+'</p>';
      var loading = $('<p class="loading">'+s.loading_text+'</p>');

      if(s.username && typeof(s.username) == "string"){
        s.username = [s.username];
      }

      var expand_template = function(info) {
        if (typeof s.template === "string") {
          var result = s.template;
          for(var key in info) {
            var val = info[key];
            result = result.replace(new RegExp('{'+key+'}','g'), val === null ? '' : val);
          }
          return result;
        } else return s.template(info);
      };

      if (s.loading_text) $(widget).append(loading);
      $(widget).bind("load", function(){
        $.getJSON(build_url(), function(data){
          if (s.loading_text) loading.remove();
          if (s.intro_text) list.before(intro);
          list.empty();

          var tweets = $.map(data.results || data, function(item){
            var join_text = s.join_text;

            // auto join text based on verb tense and content
            if (s.join_text == "auto") {
              if (item.text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
                join_text = s.auto_join_text_reply;
              } else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
                join_text = s.auto_join_text_url;
              } else if (item.text.match(/^((\w+ed)|just) .*/im)) {
                join_text = s.auto_join_text_ed;
              } else if (item.text.match(/^(\w*ing) .*/i)) {
                join_text = s.auto_join_text_ing;
              } else {
                join_text = s.auto_join_text_default;
              }
            }

            // Basic building blocks for constructing tweet <li> using a template
            var screen_name = item.from_user || item.user.screen_name;
            var source = item.source;
            var user_url = "http://"+s.twitter_url+"/"+screen_name;
            var avatar_size = s.avatar_size;
            var avatar_url = item.profile_image_url || item.user.profile_image_url;
            var tweet_url = "http://"+s.twitter_url+"/"+screen_name+"/status/"+item.id_str;
            var retweet = (typeof(item.retweeted_status) != 'undefined');
            var retweeted_screen_name = retweet ? item.retweeted_status.user.screen_name : null;
            var tweet_time = parse_date(item.created_at);
            var tweet_relative_time = relative_time(tweet_time);
            var tweet_raw_text = retweet ? ('RT @'+retweeted_screen_name+' '+item.retweeted_status.text) : item.text; // avoid '...' in long retweets
            var tweet_text = $([tweet_raw_text]).linkUrl().linkUser().linkHash()[0];

            // Default spans, and pre-formatted blocks for common layouts
            var user = '<a class="tweet_user" href="'+user_url+'">'+screen_name+'</a>';
            var join = ((s.join_text) ? ('<span class="tweet_join"> '+join_text+' </span>') : ' ');
            var avatar = (avatar_size ?
                          ('<a class="tweet_avatar" href="'+user_url+'"><img src="'+avatar_url+
                           '" height="'+avatar_size+'" width="'+avatar_size+
                           '" alt="'+screen_name+'\'s avatar" title="'+screen_name+'\'s avatar" border="0"/></a>') : '');
            var time = '<span class="tweet_time"><a href="'+tweet_url+'" title="view tweet on twitter">'+tweet_relative_time+'</a></span>';
            var text = '<span class="tweet_text">'+$([tweet_text]).makeHeart().capAwesome().capEpic()[0]+ '</span>';

            return { item: item, // For advanced users who want to dig out other info
                     screen_name: screen_name,
                     user_url: user_url,
                     avatar_size: avatar_size,
                     avatar_url: avatar_url,
                     source: source,
                     tweet_url: tweet_url,
                     tweet_time: tweet_time,
                     tweet_relative_time: tweet_relative_time,
                     tweet_raw_text: tweet_raw_text,
                     tweet_text: tweet_text,
                     retweet: retweet,
                     retweeted_screen_name: retweeted_screen_name,
                     user: user,
                     join: join,
                     avatar: avatar,
                     time: time,
                     text: text
                   };
          });

          tweets = $.grep(tweets, s.filter).slice(0, s.count);
          list.append($.map(tweets.sort(s.comparator),
                            function(t) { return "<li>" + expand_template(t) + "</li>"; }).join('')).
              children('li:first').addClass('tweet_first').end().
              children('li:odd').addClass('tweet_even').end().
              children('li:even').addClass('tweet_odd');

          if (s.outro_text) list.after(outro);
          $(widget).trigger("loaded").trigger((tweets.length === 0 ? "empty" : "full"));
          if (s.refresh_interval) {
            window.setTimeout(function() { $(widget).trigger("load"); }, 1000 * s.refresh_interval);
          }
        });
      }).trigger("load");
    });
  };
})(jQuery);
;
(function ($) {

  Drupal.behaviors.fishhound_functions = {
      attach: function(context) {
      	
				/**
				 * FRONT PAGE COLLAPSE BLOCK 
				 */
				var accordionContainer	= '.front-page-collapse-box'; 
				var accordionWraper			= accordionContainer +' .accordion-wraper'; 
				var accordionTopics			= accordionWraper +' .co'; 

				$( accordionWraper +' *:first-child').next().addClass('first-child');
        $( accordionTopics +'.first-child').addClass('opened').next('div.just-another-wraper').slideDown('slow');
				
				$( accordionTopics +' h3').click( function(){

					if( $(this).parent('div').hasClass('opened')){ 
						return false;
					}
					 
					// CLOSE ALL DIVS AND CHANGE H3 TO BASIC STATE 
					$( accordionTopics +' .just-another-wraper').slideUp('slow'); 
					$( accordionTopics).removeClass('opened'); 
					 
					// OPEN SELECTED DIV AND CHANGE H3 STATE
					$(this).parent('div').addClass('opened');
					$(this).next('div').slideDown('slow');
				});


				/**
				 * CHECK IF THERE IS ANY JQUERY CYCLE RUNNING
				 * IF IT IS TRUE CHECK IF THERE IS MORE THAN ONE PAGER ITEM OR HIDE THE PAGER
				 */
				var viewSlideshowMainContainer	= '.views_slideshow_cycle_main';				
				var viewSlideshowPagerContainer	= '.views-slideshow-controls-bottom';
				var viewSlideshowPagerItem			= '.views-slideshow-pager-field-item';
				
				var viewsSlideshowCall = $( viewSlideshowPagerContainer);
				
				if( viewsSlideshowCall.length > 0){
					viewsSlideshowCall.each( function(){
						if( $( viewSlideshowPagerItem, $(this)).length < 2){ 
							$(this).fadeOut('slow');
						}
					});
				}
      	
      	
				/**
				 * FISHHOUND TWITTER
				 */
				var twitterContainer	= '#display-fishhound-twitter:not(.fh-processed)';
				var tweetsContainer		= twitterContainer +' span.display-items';  
				var tweetsNumber			= ( ( checkTweetsNumber = $(tweetsContainer).text()) > 0) ? checkTweetsNumber : 4;
				 
				if( $(twitterContainer).length){
					$(twitterContainer).addClass('fh-processed').tweet({
						join_text: "auto",
						username: "fishhound",
						avatar_size: 48,
						count: tweetsNumber,
						auto_join_text_default: "we said,",
						auto_join_text_ed: "we",
						auto_join_text_ing: "we were",
						auto_join_text_reply: "we replied",
						auto_join_text_url: "we were checking out",
						loading_text: "loading tweets..."
					});
				}
      	
      	
				/**
				 * ADD VIDEO VALIDATION
				 */
				var fieldVideoFile	= '#edit-field-video-video-und-0-upload';
				var fieldVideoEmbed	= '#edit-field-video-video-em-und-0-value';

				$('body.page-node-add-video form#video-node-form').submit( function(){
					//e.preventDefault();
					
					// GET/SET VALUES
					var alertMessage = fieldToFocus = '';
					var valueVideoFile	= $(fieldVideoFile).val();
					var valueVideoEmbed	= $(fieldVideoEmbed).val();
					
					// IF EVERYTHING IS EMPTY
					if( ( valueVideoFile == '' && valueVideoEmbed == '')){ 
						alertMessage	= 'Sorry, you need to attach a video or add an embed code to proccess your upload.';
						fieldToFocus	= fieldVideoEmbed;
					}
					
					// DO WE HAVE MESSAGE TO DISPLAY ?
					if( alertMessage != ''){ 
						alert(alertMessage);
						return false;
					}
					
				});
				
				 
      }  
  };
})(jQuery);
;
(function($) {
  Drupal.behaviors.fh_subnavs = {
    attach: function(context) {
      $('#navigation #main-menu li:not(.fh-subnav-processed)').addClass('fh-subnav-processed').hover(
        function () {
          if(!$(this).hasClass('fh-menu-expanded')){
            //$( '.' + $(this).attr('class') + ' ul').show('fast');
            //$(this).children("ul").show('fast');
            $(this).children("ul").show();
            $(this).addClass('fh-menu-expanded');
          }
        },
        function () {
          if($(this).hasClass('fh-menu-expanded')){
            $(this).removeClass('fh-menu-expanded');
            //$( '.' + $(this).attr('class') + ' ul').hide('fast');
             //$(this).children("ul").hide('fast');
             $(this).children("ul").hide();
          }
        }
      );
      
    }
  }
})(jQuery);
;
(function ($) {

Drupal.behaviors.initColorboxDefaultStyle = {
  attach: function (context, settings) {
    $(document).bind('cbox_complete', function () {
      // Only run if there is a title.
      if ($('#cboxTitle:empty', context).length == false) {
        setTimeout(function () { $('#cboxTitle', context).slideUp() }, 1500);
        $('#cboxLoadedContent img', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideDown();
        });
        $('#cboxOverlay', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideUp();
        });
      }
      else {
        $('#cboxTitle', context).hide();
      }
    });
  }
};

})(jQuery);
;

