(function($) {

/**
 * jQuery debugging helper.
 *
 * Invented for Dreditor.
 *
 * @usage
 *   $.debug(var [, name]);
 *   $variable.debug( [name] );
 */
jQuery.extend({
  debug: function () {
    // Setup debug storage in global window. We want to look into it.
    window.debug = window.debug || [];

    args = jQuery.makeArray(arguments);
    // Determine data source; this is an object for $variable.debug().
    // Also determine the identifier to store data with.
    if (typeof this == 'object') {
      var name = (args.length ? args[0] : window.debug.length);
      var data = this;
    }
    else {
      var name = (args.length > 1 ? args.pop() : window.debug.length);
      var data = args[0];
    }
    // Store data.
    window.debug[name] = data;
    // Dump data into Firebug console.
    if (typeof console != 'undefined') {
      console.log(name, data);
    }
    return this;
  }
});
// @todo Is this the right way?
jQuery.fn.debug = jQuery.debug;

})(jQuery);
;
if(Drupal.settings.fb) {
// This function called by facebook's javascript when it is loaded.
// http://developers.facebook.com/docs/reference/javascript/
window.fbAsyncInit = function() {

  if (Drupal.settings.fb) {
    FB.init(Drupal.settings.fb.fb_init_settings);
  }

  if (FB._apiKey) {
    // Check the login status.  If offline_access granted, this
    // is the only whay to know if user has logged out of facebook.
    FB.getLoginStatus(function(response) {
      FB_JS.initFinal(response);
    });
  }
  else {
    // No application.  Not safe to call FB.getLoginStatus().
    // We still want to initialize XFBML, third-party modules, etc.
    FB_JS.initFinal({'session' : null});
  }
};

FB_JS = function(){};

/**
 * Finish initializing, whether there is an application or not.
 */
FB_JS.initFinal = function(response) {
  var status = {
    'session' : response.authResponse, // deprecated
    'auth': response.authResponse,
    'response': response
  };
  jQuery.event.trigger('fb_init', status);  // Trigger event for third-party modules.

  FB_JS.authResponseChange(response); // This will act only if fbu changed.

  FB_JS.eventSubscribe();

  FB.XFBML.parse();
}

/**
 * Tell facebook to notify us of events we may need to act on.
 */
FB_JS.eventSubscribe = function() {
  // Use FB.Event to detect Connect login/logout.
  FB.Event.subscribe('auth.authResponseChange', FB_JS.authResponseChange);

  // Q: what the heck is "edge.create"? A: the like button was clicked.
  FB.Event.subscribe('edge.create', FB_JS.edgeCreate);

}

/**
 * Helper parses URL params.
 *
 * http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
 */
FB_JS.getUrlVars = function(href) {
  var vars = [], hash;
  var hashes = href.slice(href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars[hash[0]] = hash[1];
    if (hash[0] != 'fbu')
      vars.push(hashes[i]); // i.e. "foo=bar"
  }
  return vars;
}

/**
 * Reload the current page, whether on canvas page or facebook connect.
 *
 * append fbsig, a hash of the session data, to avoid infinite reloads
 * in some cases.
 */
FB_JS.reload = function(destination) {
  // Determine url hash.
  var auth = FB.getAuthResponse();

  var fbhash;
  if (auth != null)
    fbhash = auth.signedRequest; // Use sig rather than compute a new hash.
  else
    fbhash = 0;

  // Avoid infinite reloads.  Still needed? It would be nice to do away with this code if not needed.
  ///@TODO - does not work on iframe because facebook does not pass url args to canvas frame when cookies not accepted.  http://forum.developers.facebook.net/viewtopic.php?id=77236
  var vars = FB_JS.getUrlVars(window.location.href);
  if (vars.fbhash == fbhash) {
    return; // Do not reload (again)
  }

  // Determine where to send user.
  if (typeof(destination) != 'undefined' && destination) {
    // Use destination passed in.
  }
  else if (typeof(Drupal.settings.fb.reload_url) != 'undefined') {
    destination = Drupal.settings.fb.reload_url;
  }
  else {
    destination = window.location.href;
  }

  // Split and parse destination
  var path;
  if (destination.indexOf('?') == -1) {
    vars = [];
    path = destination;
  }
  else {
    vars = FB_JS.getUrlVars(destination);
    path = destination.substr(0, destination.indexOf('?'));
  }

  // Add fbhash to params before reload.
  if (Drupal.settings.fb.reload_url_append_hash) {
    vars.push('fbhash=' + fbhash);
  }

  // Use window.top for iframe canvas pages.
  destination = vars.length ? (path + '?' + vars.join('&')) : path;

  if(Drupal.settings.fb.reload_url_fragment) {
    destination = destination + "#" + Drupal.settings.fb.reload_url_fragment;
  }

  // Feedback that entire page may be reloading.
  // @TODO improve the appearance of this, make it customizable.
  jQuery('body').prepend('<div id="fb_js_pb" class="progress"><div class="bar"><div class="filled"></div></div></div>');

  window.top.location = destination;
  //alert(destination);
};

// Facebook pseudo-event handlers.
FB_JS.authResponseChange = function(response) {
  //debugger;
  if (response.status == 'unknown') {
    // @TODO can we test if third-party cookies are disabled?
  }

  var status = {
    'changed': false,
    'fbu': null,
    'session': response.authResponse, // deprecated,  still needed???
    'auth': response.authResponse, // still needed???
    'response' : response
  };

  if (response.authResponse) {
    status.fbu = response.authResponse.userID;
    if (Drupal.settings.fb.fbu != status.fbu) {
      // A user has logged in.
      status.changed = true;
    }
  }
  else if (Drupal.settings.fb && Drupal.settings.fb.fbu) {
    // A user has logged out.
    status.changed = true;

    // Sometimes Facebook's invalid cookies are left around.  Let's try to clean up their crap.
    // Can get left behind when third-party cookies disabled.
    // @TODO: Still needed with new oauth??? Have cookies been renamed (fbsr_...)???
    FB_JS.deleteCookie('fbs_' + FB._apiKey, '/', '');
    FB_JS.deleteCookie('fbs_' + Drupal.settings.fb.apikey, '/', '');
  }

  if (status.changed) {
    // fbu has changed since server built the page.
    jQuery.event.trigger('fb_session_change', status);

    // Remember the fbu.
    Drupal.settings.fb.fbu = status.fbu;
  }

};

// edgeCreate is handler for Like button.
FB_JS.edgeCreate = function(href, widget) {
  var status = {'href': href};
  FB_JS.ajaxEvent('edge.create', status);
};

// JQuery pseudo-event handler.
FB_JS.sessionChangeHandler = function(context, status) {
  // Pass data to ajax event.
  var data = {
    'event_type': 'session_change'
  };

  if (status.session) {
    data.fbu = status.session.userID;
    // Suppress facebook-controlled session.
    data.fb_session_handoff = true;
  }

  FB_JS.ajaxEvent(data.event_type, data);
  // No need to call window.location.reload().  It will be called from ajaxEvent, if needed.
};


// Helper to pass events via AJAX.
// A list of javascript functions to be evaluated is returned.
FB_JS.ajaxEvent = function(event_type, request_data) {
  if (Drupal.settings.fb.ajax_event_url) {

    // Session data helpful in ajax callbacks.  See fb_settings.inc.
    // request_data.fb_js_session = JSON.stringify(FB.getSession()); // FB.getSession() FAILS! REMOVE or REPLACE.
    if (typeof(Drupal.settings.fb_page_type) != 'undefined') {
      request_data.fb_js_page_type = Drupal.settings.fb_page_type;
    }

    // FB._apikey might be an apikey or might be an appid!
    if (FB._apiKey == Drupal.settings.fb.fb_init_settings.appId ||
        FB._apiKey == Drupal.settings.fb.fb_init_settings.apiKey) {
      request_data.apikey = Drupal.settings.fb.fb_init_settings.apiKey; // deprecated
      request_data.appId = Drupal.settings.fb.fb_init_settings.appId;
    }

    // Other values to pass to ajax handler.
    if (Drupal.settings.fb.controls) {
      request_data.fb_controls = Drupal.settings.fb.controls;
    }

    jQuery.ajax({
      url: Drupal.settings.fb.ajax_event_url + '/' + event_type,
      data : request_data,
      type: 'POST',
      dataType: 'json',
      success: function(js_array, textStatus, XMLHttpRequest) {
        if (js_array.length > 0) {
          for (var i = 0; i < js_array.length; i++) {
            eval(js_array[i]);
          }
        }
        else {
          if (event_type == 'session_change') {
            // No instructions from ajax, reload entire page.
            FB_JS.reload();
          }
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // Unexpected error (i.e. ajax did not return json-encoded data).
        var headers = jqXHR.getAllResponseHeaders(); // debug info.
        var responseText = jqXHR.responseText; // debug info.
        debugger;
        // @TODO: handle error, but how?
      }
    });
  }
};

// Delete a cookie.
// Facebook's JS SDK attempts to delete, but I'm not convinced it always works.
FB_JS.deleteCookie = function( name, path, domain ) {
  document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
};


/**
 * Drupal behaviors hook.
 *
 * Called when page is loaded, or content added via javascript.
 */
(function ($) {
  Drupal.behaviors.fb = {
    attach : function(context) {
      // Respond to our jquery pseudo-events
      var events = jQuery(document).data('events');
      if (!events || !events.fb_session_change) {
	jQuery(document).bind('fb_session_change', FB_JS.sessionChangeHandler);
      }

      // Once upon a time, we initialized facebook's JS SDK here, but now that is done in fb_footer().

      if (typeof(FB) != 'undefined') {
        // Render any XFBML markup that may have been added by AJAX.
        $(context).each(function() {
          var elem = $(this).get(0);
          FB.XFBML.parse(elem);
        });
      }

      // Markup with class .fb_show should be visible if javascript is enabled.  .fb_hide should be hidden.
      jQuery('.fb_hide', context).hide();
      jQuery('.fb_show', context).show();
    }
  };

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

  Drupal.behaviors.fh_admin_dashboard = {
      attach: function(context) {
        // Review Pending Submissions: Approve, Delete
        $('div.admin-op p').hide();
        $('a.op-confirm').hide();
        $('a.op-cancel').hide();

        $('a.op-prompt').live('click', function(e) {
            e.preventDefault();
            $(this).hide();
            $(this).siblings('div.admin-op p').show();
            $(this).siblings('a.op-confirm').show();
            $(this).siblings('a.op-cancel').show();
        });

        $('a.op-cancel').live('click', function(e) {
            e.preventDefault();
            $(this).siblings('div.admin-op p').hide();
            $(this).siblings('a.op-confirm').hide();
            $(this).siblings('a.op-prompt').show();
            $(this).hide();
        });

        $('a.op-confirm').live('click', function(e) {
          e.preventDefault();
          var url = $(this).attr('href');
          $.get(url, function(data) {
            $('a[href=' + url + ']').parent().parent().parent().replaceWith('<div class="message">'+data.data+'</div>');
          });
        });

        // Newly: Set up complete/incomplete.
        $('.view-admin-dash-newly td.views-field-entity-id-6 a, .view-admin-dash-newly td.views-field-entity-id-9 a').live('click', function(e) {
          e.preventDefault();
          var url = $(this).attr('href');
          $.get(url, function(data) {
            $('a[href=' + url + ']').replaceWith('<div class="message">'+data.data+'</div>');
          });
        });

      }
  };

})(jQuery);
;
(function ($) {
  Drupal.behaviors.fh_product_showcase = {
    attach: function(context,settings) {
      $('#send-me-gear-modal a.fake-continue').click(function(e){
        e.preventDefault();
      });
      $('#send-me-gear-modal a.modal-close-btn').click(function(e){
        $('.ui-dialog-titlebar-close').click();
      });
      if (jQuery.ui != undefined && jQuery.ui.dialog) {
        $('#product_showcase_video_modal_container').dialog({
          width: 'auto',
          modal: true,
          stack: false,
          autoOpen:false,
          close: function(ev, ui) { $(this).html(''); }
        });
        $('.send-me-gear-modal').dialog({
          width: '550',
          modal: true,
          stack: false,
          autoOpen:false
          //close: function(ev, ui) { $(this).html(''); }
        });
        $('#fh-upgrade-gear-modal').dialog({
          width: '550',
          modal: true,
          stack: false,
          autoOpen:false
        });
        $('body.guest input.trigger-product-premium-modal', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            $('#fh-upgrade-gear-modal').dialog('open');
            e.preventDefault();
          });
        });
        $('.pane-gear-videos .views-field-field-ps-video-embed a:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            e.preventDefault();
            var v_id = $(this).attr('href');
            var content = '<iframe width="560" height="315" src="http://www.youtube.com/embed/'+v_id+'?autoplay=1" frameborder="0" allowfullscreen></iframe>';
            $('#product_showcase_video_modal_container').html(content);
            //$('#step4-section-modal-container').html('<iframe width="560" height="315" src="'+url+'" frameborder="0" autoplay="1" allowfullscreen></iframe>');
            $('#product_showcase_video_modal_container').dialog("open");
          });
        });
        $('body.node-type-gear-product #gear-discount-content').dialog({
          modal: true,
          stack: false,
          autoOpen:false,
          position: 'center',
          width: '500'
        });
        $('body.node-type-gear-product .views-field-nothing-1 a:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            e.preventDefault();
            $('body.node-type-gear-product #gear-discount-content').dialog("open");
          })
        })
        $('body.node-type-gear-product .pane-node-field-ps-zoom-image').dialog({
          width: 'auto',
          modal: true,
          stack: false,
          autoOpen:false,
          position: 'center'
        });
        $('body.node-type-gear-product .field-name-field-ps-prod-image a:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
        	e.preventDefault();
            $('body.node-type-gear-product .pane-node-field-ps-zoom-image').dialog("open");
          })
        })
      }
    }
  }
}(jQuery));
(function ($) {
  function disable_fields(){
    $('#edit-first-name').attr('disabled', 'disabled');
    $('#edit-last-name').attr('disabled', 'disabled');	
    $('#edit-address-1').attr('disabled', 'disabled');
    $('#edit-address-2').attr('disabled', 'disabled');	
    $('#edit-city').attr('disabled', 'disabled');
    $('#edit-state').attr('disabled', 'disabled');
    $('#edit-zipcode').attr('disabled', 'disabled');
    $('#edit-shirt-size').attr('disabled', 'disabled');	
  }
  function enable_fields(){
	$('#edit-first-name').removeAttr('disabled');
	$('#edit-last-name').removeAttr('disabled');
	$('#edit-address-1').removeAttr('disabled');
	$('#edit-address-2').removeAttr('disabled');
	$('#edit-city').removeAttr('disabled');
	$('#edit-state').removeAttr('disabled');
	$('#edit-zipcode').removeAttr('disabled');
	$('#edit-shirt-size').removeAttr('disabled');
  }
  function check_fields(){
	var number_of_emails = 5;
	var fields_filled = 0;
    for(var i=0; i<number_of_emails; i++){
      if($('#edit-email-address-'+i).val() == ''){
        disable_fields();
        break;
      }else{
        fields_filled++;
      }
    }
    if(fields_filled == number_of_emails){
      enable_fields();
    }
  }
  Drupal.behaviors.fishhound_refer_friend = {
    attach: function(context,settings) {
      check_fields();
      $('#edit-friends-email-addresses .form-type-textfield input').keyup(function(){
    	check_fields();
      });
    }
  }
}(jQuery));
(function ($) {
  // .live() and Drupal behaviors do not mix.
        $('a[href*="user-dashboard/add-fav-water"]').live('click', function(e) {
          e.preventDefault();
          var my_obj = $(this);
          var url = $(this).attr('href');
          $.get(url, function(data) {
            // if the add-to-dash link was not the one on the water page, change it to a remove-from-dash link
            if(!my_obj.hasClass('water-page-link')) {
              $('a[href=' + url + ']').parent().html(data.data);
              // Keep the user_favorite_waters array up to date so dynamic stuff like the water bigmap doesn't get confused.
              if (Drupal.settings.user_favorite_waters) {
                var nid = url.split('/').pop();
                Drupal.settings.user_favorite_waters[nid] = !(Drupal.settings.user_favorite_waters[nid]);
              }
            }
            // if the add-to-dash link was the one on the water page, hide it and update the listing in the left sidebar
            else {
              my_obj.closest('.water-node-add').hide('slow');
              
              var new_row = '<div class="views-row views-row-1"><div class="views-field views-field-entity-id-1"><div class="field-content">' + data.data + '</div></div></div>';
              $(new_row)
                .hide()
                .appendTo('.view-water-my-waters-sidebar .view-content')
                .fadeIn('slow');
            }
          });
        });
        
        // this handles the changes across tabs
        $('a[href*="user-dashboard/fetch-data"]').live('click', function(e) {
          e.preventDefault();
          var url = $(this).attr('href');
          $.get(url, function(data) {
            $('a[href*=' + url + ']').parent().children().removeClass('active');
            $('a[href*=' + url + ']').addClass('active');
            /*if(url.indexOf('hatch_tracker') != -1) {
              $('.hatch-alert-table').html(data.data);
            }
            else if(url.indexOf('bait_tracker') != -1) {
              $('.bait-alert-table').html(data.data);
            }
            else if(url.indexOf('migration') != -1) {
              $('.migration-table').html(data.data);
            }*/
            $('.user-dashboard-content').html(data.data);
          });
        });
        
        // if the remove button on the user dash page is clicked, remove that row,
        // remove the item from the list in the left column,
        // and remove all related content in migration & hatch tables
        $('a.inline-remove').live('click', function(e) {
          $(this).closest('tr').hide('slow');
          $(this).removeClass('inline-remove');
          var water_path = $(this).attr('class');
          $('.view-water-my-waters-sidebar a[href*=' + water_path + ']').parent().hide('slow');
          var water_path_class = water_path.replace('/', '-');
          $('tr[class*=' + water_path_class + ']').hide('slow');
          $('td[class*=' + water_path_class + ']').parent().hide('slow');
        });
        
        $('a.confirm-remove').live('click', function(e) {
          e.preventDefault();
          var url = $(this).attr('href');
          var title = $(this).parent().parent().children()[0].innerHTML;
          $( "#confirm-dialog-placeholder" ).html("Are you sure you want to delete " + title + "?");
          $( "#confirm-dialog-placeholder" ).dialog({
            resizable: false,
            height:140,
            modal: true,
            buttons: {
              "Delete item": function() {
                $.get(url, function(data) {
                  //if successful delete element otherwise alert about the error
                  $('table a[href="'+ url +'"]').parent().parent().parent().hide();
                });
                $( this ).dialog( "close" );
              },
              Cancel: function() {
                $( this ).dialog( "close" );
              }
            }
          });
        });
        $('.phone-app-no-thanks a').live('click', function(e){
          var c_name = 'phone-app-ad'
          var value = 'closed';
          var exdays = 100000;
          var exdate=new Date();
          exdate.setDate(exdate.getDate() + exdays);
          var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
          document.cookie=c_name + "=" + c_value;
          e.preventDefault();
          $('.catch-phone-app-try').hide('slow');
        });
  
})(jQuery);
;
(function($) {
	
	/*
	 * get widget link click 
	 */
	$('#get-widget').live(
			'click',
			function(e) {
				e.preventDefault();
				var embedded_height = 0;
				var embedded_width  = 0;
				var size = 1;
				//check widget size 
				switch (jQuery("#wsizeform input:radio:checked").val()){
					case '250 X 400':
						embedded_width = 250;
						 embedded_height  = 400;
						size = 1;			
					break;
					case '250 X 600':
						embedded_width = 250;
						embedded_height  = 600;
						size = 2;
					break;
					case '300 X 250':
						embedded_width = 300;
						embedded_height = 250;
						size = 3;
					break;
					default:
						embedded_width	 = 250;
						embedded_height  = 400;
					break;
				}
				
				//ajax call url
				var src = site_url+'/widgets/mywidget/'+size;
				//build iframe embedded code
				var embedded = '<iframe frameborder="0" height="'+ embedded_height + '" src="' + src+ '"; target="_blank" align="center" width="'+ embedded_width+ '" scrolling="auto"; bgcolor="#FFFFFF"> </iframe>';
				//fill textarea
				$("#wdialog-placeholder").html(htmlEscape(embedded));
				//open dialog box
				$("#wdialog-placeholder").dialog( {
					resizable : false,
					height : 250,
					width : 250,
					modal : true,
					buttons : {
						Cancel : function() {
							$(this).dialog("close");
						}
					}
				});
	});
	
	/*
	 * submit action
	 */	
	$('#widget-submit').live(
			'click',
			function(e) {
				e.preventDefault();
				var formId="fh-widgets-fishing-report-form";
				jQuery("#widget-value").val(jQuery("#widget-value").val());
				var zipcode = jQuery("#widget-value").val();
				var submitURL = site_url+'/widgets/fh/us_'+zipcode+'_200mi';
				jQuery.ajax( {
					async : false,
					type : "GET",
					url : submitURL,
					data : "zipcode=" + zipcode,
					dataType : "json",
					cache : false,
					//if successful ajax call
					success : function(formResponse) {
						//print results
						//$('#result-placeholder').html(formResponse);
						$('#result-placeholder-'+holder).html(formResponse);
						//render starts
						render_stars();
					},
					error : function(jqXHR, textStatus, errorThrown) {
						//alert("textStatus " + textStatus);
				}
		});
	});
	/*
	 * submit action 250*600
	 */	
	$('#widget-submit-250X600').live(
			'click',
			function(e) {
				e.preventDefault();
				var zipcode = jQuery("#widget-value-250X600").val();
				var submitURL = site_url+'/widgets/fh/us_'+zipcode+'_200mi';
				jQuery.ajax( {
					async : false,
					type : "GET",
					url : submitURL,
					data : "zipcode=" + zipcode,
					dataType : "json",
					cache : false,
					//if successful ajax call
					success : function(formResponse) {
						//print results
						//$('#result-placeholder').html(formResponse);
						$('#result-placeholder-'+holder).html(formResponse);
						//render starts
						render_stars();
					},
					error : function(jqXHR, textStatus, errorThrown) {
						//alert("textStatus " + textStatus);
				}
		});
	});
	
	/*
	 * submit action 300*250
	 */	
	$('#widget-submit-300X250').live(
			'click',
			function(e) {
				e.preventDefault();
				var zipcode = jQuery("#widget-value-300X250").val();
				var submitURL = site_url+'/widgets/fh/us_'+zipcode+'_200mi';
				jQuery.ajax( {
					async : false,
					type : "GET",
					url : submitURL,
					data : "zipcode=" + zipcode,
					dataType : "json",
					cache : false,
					//if successful ajax call
					success : function(formResponse) {
						//print results
						//$('#result-placeholder').html(formResponse);
						$('#result-placeholder-'+holder).html(formResponse);
						//render starts
						render_stars();
					},
					error : function(jqXHR, textStatus, errorThrown) {
						//alert("textStatus " + textStatus);
				}
		});
	});
	
	
	/*
	 * escape chars to present in textarea
	 */
	function htmlEscape(s){
		s = s.replace(/&/g,'&');
		s = s.replace(/>/g,'&gt;');
		s = s.replace(/</g,'&lt;');
		return s;
	}
	
	/*
	 * render starts on iframe
	 */
	function render_stars(){
    $.each($('.star-1 .on'), function(){
      if($(this).html() != '' && $(this).html != null) {
        stars = '<div class="widget-stars">';
        for(i = 0; i < $(this).html(); i++) {
          stars = stars + '<div class="yelow-star">&nbsp;</div>';
        }
        for(i = $(this).html(); i < 5; i++){
          stars = stars + '<div class="grey-star">&nbsp;</div>';
        }
        stars = stars + '</div>';
        $(this).html(stars);
        title_link = $(this).parent().parent().parent().parent().children('.views-field-title').html();
        $(this).parent().parent().parent().parent().children('.views-field-title').html(title_link + stars);
      }
    });
    
    no_rating = '<div class="widget-stars"><div class="grey-star">&nbsp;</div><div class="grey-star">&nbsp;</div><div class="grey-star">&nbsp;</div><div class="grey-star">&nbsp;</div><div class="grey-star">&nbsp;</div></div>';
    $.each($('.views-field-entity-id-1'), function(){
      rating = $(this).html();
      if( rating.indexOf('No rating') != -1) {
        $(this).parent().children('.views-field-title').html($(this).parent().children('.views-field-title').html() + no_rating);
      }
    });
                  
    $('.widget-message').hide('slow');
  }
	
	//end file
})(jQuery);

;
( function($) {
  $.fn.friendshipRequested = function(data) {
    $('#wizard-dialog-container').html('Friendship Request Sent');
    $('#wizard-dialog-container').dialog({
      height: 140,
      modal: true
    });
  }
  $.fn.friendshipRequestFailed = function(data) {
    $('#wizard-dialog-container').html('Friendship Request Failed. Please Try Again Later.');
    $('#wizard-dialog-container').dialog({
      height: 140,
      modal: true
    });
  }
	Drupal.behaviors.fishhound_wizard = {
		attach : function(context, settings) {
		  
		  $('#edit-fake-upload-photo-button:not(.fh-processed)', context).addClass('fh-processed').click(function(e) {
		    e.preventDefault();
				$('#edit-upload-photo-file-upload').click();
			});
			$('#edit-upload-photo-file-upload:not(.fh-processed)', context).addClass('fh-processed').change(function() {
				var path = $(this).val();
				path = path.replace('C:\\fakepath\\', '');
				$('#edit-fake-upload-photo-path').val(path);
			});
			$('#edit-upload-photo-file-remove-button:not(.fh-processed)', context).addClass('fh-processed').bind('mousedown', function() {
				$('#edit-fake-upload-photo-path').val('');
				return false;
			});
			$.each($('#edit-about-wrapper .form-textarea'), function(i, obj) {
				if($(obj).val() == 'Tell us about yourself') {
					$(obj).addClass('form-item-empty');
				}
			});
			$('#edit-about-wrapper .form-textarea').focus(function() {
				if($(this).val() == 'Tell us about yourself') {
					$(this).removeClass('form-item-empty');
					$(this).val('');
				}
			});
			$('#edit-about-wrapper .form-textarea').blur(function() {
				if($(this).val() == '') {
					$(this).addClass('form-item-empty');
					$(this).val('Tell us about yourself');
				}
			});
			$.each($('#edit-rods-fieldset .form-text'), function(i, obj) {
				if($(obj).val() == 'Enter your favorite fishing gear') {
					$(obj).addClass('form-item-empty');
				}
			});
			$('#edit-rods-fieldset .form-text').focus(function() {
				if($(this).val() == 'Enter your favorite fishing gear') {
					$(this).removeClass('form-item-empty');
					$(this).val('');
				}
			});
			$('#edit-rods-fieldset .form-text').blur(function() {
				if($(this).val() == '') {
					$(this).addClass('form-item-empty');
					$(this).val('Enter your favorite fishing gear');
				}
			});
			$.each($('#edit-flies-fieldset .form-text'), function(i, obj) {
				if($(obj).val() == 'Enter your favorite flies & lures') {
					$(obj).addClass('form-item-empty');
				}
			});
			$('#edit-flies-fieldset .form-text').focus(function() {
				if($(this).val() == 'Enter your favorite flies & lures') {
					$(this).removeClass('form-item-empty');
					$(this).val('');
				}
			});
			$('#edit-flies-fieldset .form-text').blur(function() {
				if($(this).val() == '') {
					$(this).addClass('form-item-empty');
					$(this).val('Enter your favorite flies & lures');
				}
			});
			$.each($('#edit-species-fieldset .form-text'), function(i, obj) {
				if($(obj).val() == 'Enter your favorite fish species') {
					$(obj).addClass('form-item-empty');
				}
			});
			$('#edit-species-fieldset .form-text').focus(function() {
				if($(this).val() == 'Enter your favorite fish species') {
					$(this).removeClass('form-item-empty');
					$(this).val('');
				}
			});
			$('#edit-species-fieldset .form-text').blur(function() {
				if($(this).val() == '') {
					$(this).addClass('form-item-empty');
					$(this).val('Enter your favorite fish species');
				}
			});
			//step 4
			$('.step4-section .form-select:not(.fh-processed)', context)
			.addClass('fh-processed').each(function(){
			  var section_index = $(this).attr('id').substr('24');
			  if($(this).val() == 'image'){
			    $('.form-item-step-4-video-section'+section_index).hide();
			    $('.form-item-step-4-enlarged-section'+section_index).show();
			    $('.form-item-step-4-ext-link'+section_index).hide();
			  }else if($(this).val() == 'video'){
			    $('.form-item-step-4-video-section'+section_index).show();
          $('.form-item-step-4-enlarged-section'+section_index).hide();
          $('.form-item-step-4-ext-link'+section_index).hide();
			  }else{
			    $('.form-item-step-4-video-section'+section_index).hide();
			    $('.form-item-step-4-enlarged-section'+section_index).hide();
			    $('.form-item-step-4-ext-link'+section_index).show();
			  }
        $(this).change(function(e) {
          var section_index = $(this).attr('id').substr('24');
          if($(this).val() == 'image'){
            $('.form-item-step-4-video-section'+section_index).hide();
            $('.form-item-step-4-enlarged-section'+section_index).show();
            $('.form-item-step-4-ext-link'+section_index).hide();
          }else if($(this).val() == 'video'){
            $('.form-item-step-4-video-section'+section_index).show();
            $('.form-item-step-4-enlarged-section'+section_index).hide();
            $('.form-item-step-4-ext-link'+section_index).hide();
          }else{
            $('.form-item-step-4-video-section'+section_index).hide();
            $('.form-item-step-4-enlarged-section'+section_index).hide();
            $('.form-item-step-4-ext-link'+section_index).show();
          }
        });
			});
			
      if (jQuery.ui != undefined && jQuery.ui.dialog) {
        $('#step4-section-modal-container').dialog({
          width: 'auto',
          modal: true,
          stack: false,
          autoOpen:false,
          close: function(ev, ui) { $(this).html(''); }
        });
        $('a.fh-wizard-enlarge:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            var content = $('#'+url).html().replace('autoplay_replace', 'autoplay=1');
            $('#step4-section-modal-container').html(content);
            //$('#step4-section-modal-container').html('<iframe width="560" height="315" src="'+url+'" frameborder="0" autoplay="1" allowfullscreen></iframe>');
            $('#step4-section-modal-container').dialog("open");
          });
        });
      }
      //step3
      $('#members-in-your-waters .add-friend a').click(function(e){
        e.preventDefault();
        $('.add-member', $(this).parent().parent()).click();
      });
		}
	}
	/*Drupal.behaviors.fileButtons = {
	 attach: function(context) {
	 $('#edit-upload-photo-file-remove-button', context).bind( 'mousedown', function(){
	 alert('with behaviors 2');
	 $('#edit-fake-upload-photo-path').val('');
	 return  false;
	 });
	 }
	 }
	 $(document).ready(function() {
	 $('#edit-upload-photo-file-remove-button').live('mousedown', function(){
	 alert('with live');
	 $('#edit-fake-upload-photo-path').val('');
	 return false;
	 });
	 });*/
}(jQuery));
(function ($) {
  Drupal.behaviors.fishhound_community = {
    attach: function(context,settings) {
      
      //load modal
      if (jQuery.ui != undefined && jQuery.ui.dialog) {
        $('#add-edit-caption-modal').dialog({
            autoOpen: false,
            resizable: false,
            height: "auto",
            width: 320,
            padding: 20,
            modal: true,
            title: "Add/Edit Caption",
            position: "center"
        });
        $('#album-list-modal-container').dialog({
          autoOpen: false,
          resizable: false,
          height: "auto",
          width: 360,
          padding: 20,
          modal: true,
          position: "center"
        });
        
        $('#block-views-photo_albums-block_photos .views-field-edit-node a:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ $(this).click(function(e) {
          e.preventDefault();
          var caption = $('.views-field-body .field-content', $(this).parent().parent().parent()).html();
          var href = $(this).attr('href');
          var nid = href.substring(6, href.indexOf('/', 6));
          $('#add-edit-caption-modal').html('<div>Loading...</div>');
          $.ajax({
            // Need to specify JSON data.
            dataType: 'json',
            url: '/ajax/community/photo-caption-form/'+nid,
            success: function(response){
              // Call all callbacks.
              $('#add-edit-caption-modal').html(response);
              Drupal.attachBehaviors($('#add-edit-caption-modal'), settings);
            }
          });
          $('#add-edit-caption-modal').dialog("open");
        });
        });
        
        $('#block-views-my_media-block_community_videos .views-field-edit-node a:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ $(this).click(function(e) {
          e.preventDefault();
          var caption = $('.views-field-body .field-content', $(this).parent().parent().parent()).html();
          var href = $(this).attr('href');
          var nid = href.substring(6, href.indexOf('/', 6));
          $('#add-edit-caption-modal').html('<div>Loading...</div>');
          $.ajax({
            // Need to specify JSON data.
            dataType: 'json',
            url: '/ajax/community/video-caption-form/'+nid,
            success: function(response){
              // Call all callbacks.
              $('#add-edit-caption-modal').html(response);
              Drupal.attachBehaviors($('#add-edit-caption-modal'), settings);
            }
          });
          $('#add-edit-caption-modal').dialog("open");
        });
        });
        
        $('a.trigger-popup:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ $(this).click(function(e) {
          e.preventDefault();
          $ajax_loader = '<div style="margin: 0 140px;background:url(/misc/throbber.gif) 0 -15px no-repeat;height: 20px; width: 20px;"></div>'
          $('#request-message-confirm-action-container').html($ajax_loader);
          var href = $(this).attr('href');
            $.ajax({
	          url: href,
	          success: function(response){
	            // Call all callbacks.
	        	  $('#request-message-confirm-action-container').html($('#content', response).html());
	          },
	          error: function(jqXHR, textStatus, errorThrown){
	            $('#request-message-confirm-action-container').html('The relationship could not be approved. This user may be already added to your friends.');
	          }
	        });
          $('#request-message-confirm-action-container').dialog({
              resizable: false,
              height: "auto",
              width: 320,
              padding: 20,
              modal: true,
              position: "center"
          });
        });
        });
        
        $('#community-landing-featured-video-container').dialog({
          autoOpen: false,
          resizable: false,
          height: "auto",
          width: 560,
          padding: 20,
          modal: true,
          position: "center",
          close: function(ev, ui) { $(this).html(''); }
        });
        
        $('.community-landing-fv-thumb-img a:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            $('#community-landing-featured-video-container').html('<iframe width="560" height="315" src="'+url+'" frameborder="0" autoplay="1" allowfullscreen></iframe>');
            $('#community-landing-featured-video-container').dialog("open");
          });
        });
        
        $('.view-photo-albums .delete-disabled', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            e.preventDefault();
            $('#album-list-modal-container').html('In order to delete an album you must first delete all photos in it.');
            $('#album-list-modal-container').dialog('open');
          });
        });
        
        /*$('#add-friend-first-modal').dialog({
          autoOpen: false,
          resizable: false,
          height: "auto",
          width: 360,
          padding: 20,
          modal: true,
          position: "center",
        });
        $('a.add-friend-first-modal:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            e.preventDefault();
            $('#add-friend-first-modal').dialog("open");
          });
        });
        $('#friendship-approval-needed-modal').dialog({
          autoOpen: false,
          resizable: false,
          height: "auto",
          width: 360,
          padding: 20,
          modal: true,
          position: "center",
        });
        $('a.friendship-approval-needed-modal:not(.fh-processed)', context)
        .addClass('fh-processed').each(function(){ 
          $(this).click(function(e) {
            e.preventDefault();
            $('#friendship-approval-needed-modal').dialog("open");
          });
        });*/
      }
      
      // add compose message button to message listing page
      if($('#privatemsg-list-form .container-inline').length) {
        if(!$('#privatemsg-list-form .container-inline').hasClass('compose-link-added')){
          $('#privatemsg-list-form .container-inline').addClass('compose-link-added');
          $('#privatemsg-list-form .container-inline').append('<a href="/community/messages/new">Compose a new message</a>');
        }
      }
      else {
        $('#privatemsg-list-form').prepend('<div class="container-inline"><a href="/community/messages/new">Compose a new message</a></div>');
      }
      
    }
  
  }
  
  $(window).scroll(function() {
    var top = $(window).scrollTop();
    var docheight = $(document).height();
    var windowheight = $(window).height();
    if($(document).height() - $(window).height() - $(window).scrollTop() < 150) {
  	  if($('body').hasClass('page-community-wall')) {
  		  var cur_page = $('#view-wall-posts-current-page').val();
  		  var total_pages = $('#view-wall-posts-total-pages').val();
        if(cur_page < total_pages -1){
          var page = parseInt(cur_page) + 1;
          var uid = $('#view-wall-posts-uid').val();
  		    $("#community-wall-ajax-loader").show();
          $.ajax({
  		      url: '/ajax/community/wall/' + uid + '/' + page,
  		      success: function(response){
  		        // Call all callbacks.
  		        if($('#view-wall-posts-current-page').val() < page){
  		      	  $('#view-wall-posts-current-page').val(page);
  		      	  $('.view-wall-posts .view-content').append($('.view-content',response).html());
  		        }
  		      },
  		      complete:function() {
  		        $("#community-wall-ajax-loader").hide();
  		      }
          });
  		  }
  	  }
  	  else if($('body').hasClass('page-community-newsfeed')) {
  		  var cur_page = $('#view-wall-posts-current-page').val();
  		  var total_pages = $('#view-wall-posts-total-pages').val();
        if(cur_page < total_pages -1) {
  		    var page = parseInt(cur_page) + 1;
  		    var filter_val = $('#edit-news-feed-filter').val();
  		    $("#community-wall-ajax-loader").show();
  		    $.ajax({
  	        url: '/ajax/community/newsfeed/' + page + '/' + filter_val,
            success: function(response) {
              // Call all callbacks.
              if($('#view-wall-posts-current-page').val() < page) {
            	  $('#view-wall-posts-current-page').val(page);
            	  $('.view-wall-posts .view-content').append($('.view-content',response).html());
              }
            },
  		      complete:function() {
  		        $("#community-wall-ajax-loader").hide();
  		      }
  	      });
        }
  	  }
    }
  });
  
  
  //show wall post remove link when hovering over the item
  $('.wall-post-main').live({
    mouseover: function() {
      $(this).find('.remove-post').show();
    },
    mouseout: function() {
      $(this).find('.remove-post').hide();
    }
  });
  
  //show comment remove link when hovering over the item
  $('.wall-post-comment-content').live({
    mouseover: function() {
      $(this).find('.remove-post-comment').show();
    },
    mouseout: function() {
      $(this).find('.remove-post-comment').hide();
    }
  });
  
  /*
   * Remove comment from a wall post
   */
  $('a[href*="community/remove-wall-comment"]').live('click', function(e) {
    e.preventDefault();
    var my_obj = $(this);
    var url = $(this).attr('href');
    $.get(url, function(data) {
      if(data.data == 'success') {
        my_obj.closest('.comment').hide('slow');
      }
    });
  });
  
  /*
   * Remove a wall post
   */
  $('a[href*="community/remove-wall-post"]').live('click', function(e) {
    e.preventDefault();
    var my_obj = $(this);
    var url = $(this).attr('href');
    $.get(url, function(data) {
      if(data.data == 'success') {
        my_obj.closest('.views-row').hide('slow');
      }
    });
  });

  $(document).ready(function() {
    // Hide comments when there are >3 on wall posts and add a "View all comments" link
    $('.wall-post-content .comment-wrapper').each(function(index) {
      $(this).children('.comment').slice(0, -3).hide();
      var num_comments = $(this).children('.comment').length;
      if(num_comments > 3) {
        //$(this).children('.clearfix:not(.comment)').hide();
        //$(this).children('.comment').last().after('<div class="show-more-comments"><a href="#">View all comments</a></div>');
        $(this).addClass('has-view-more').prepend('<div class="show-more-comments"><a href="#">View all comments</a></div>');
      }
    });
    
    // Hide comment submit buttons.  These forms submit on enter key being pressed
    $('.wall-post-first-comment-form input[type="submit"], .wall-post-comment-content input[type="submit"]').hide();
    $('.wall-post-first-comment-form textarea, .wall-post-comment-content textarea').css('color', 'gray');
  });
  
  $(document).ajaxStop(function() {
    // Hide comments when there are >3 on wall posts and add a "View all comments" link
    $('.wall-post-content .comment-wrapper').each(function(index) {
      $(this).not('.has-view-more').children('.comment').slice(0, -3).hide();
      var num_comments = $(this).children('.comment').length;
      if(num_comments > 3) {
        //$(this).children('.clearfix:not(.comment)').hide();
        //$(this).children('.comment').last().after('<div class="show-more-comments"><a href="#">View all comments</a></div>');
        $(this).not('.has-view-more').addClass('has-view-more').prepend('<div class="show-more-comments"><a href="#">View all comments</a></div>');
      }
    });
  });
  
  // reveal more comments when user clicks "View all comments"
  $('.show-more-comments a').live('click', function(e) {
    e.preventDefault();
    var my_obj = $(this);
    my_obj.parent().hide();
    my_obj.parent().parent().children('.comment').show('slow');
    //my_obj.parent().parent().children('.clearfix').show('slow');
  });
  
  //.live() and Drupal behaviors do not mix.
  /*$('a.ajax-form-link').live('click', function(e) {
    e.preventDefault();
    var my_obj = $(this);
    var url = $(this).attr('href');
    $.get(url, function(data) {
      $('a[href=' + url + ']').parent().next('#favorite-rods-list').html(data.data);
    });
  });*/
  
  $('body.page-community-wall #statedrilldown-water-replace select').live('change', function(e) {
    window.location = '/user-water-update/' + $(this).val() + '?destination=community/wall';
  });
  
  $('body.page-community-newsfeed #statedrilldown-water-replace select').live('change', function(e) {
    window.location = '/user-water-update/' + $(this).val() + '?destination=community/wall';
  });
  
  $('body.page-community-fishing-reports #statedrilldown-water-replace select').live('change', function(e) {
    var url = '/user-dashboard/add-fav-water/' + $(this).val();
    $.get(url, function(data) { window.location = '/community/fishing-reports'; });
  });
  
  $('#post-wall-update').live('click', function(e) {
    e.preventDefault();
    $('#location-geo-phase1-statedrilldown').toggle('slow');
  });
  
  $('#fishing-reports-add-water-toggle').live('click', function(e) {
    e.preventDefault();
    $('#fishing-report-water-select').toggle('slow');
  });
  
  // change background color of buttons on message listing page when messages and selected/deselected
  $('.privatemsg-list input[type="checkbox"]').live('change', function(e) {
    if($('.privatemsg-list input[type="checkbox"]').is(":checked")) {
      /*$('#privatemsg-list-form .container-inline input').css('background-color', '#355274');*/
      $('#privatemsg-list-form .container-inline input').removeClass('hide-button');
      $('#privatemsg-list-form .container-inline .fake-button').addClass('hide-button');
    }
    else {
      /*$('#privatemsg-list-form .container-inline input').css('background-color', '#6e8ba9');*/
      $('#privatemsg-list-form .container-inline input').addClass('hide-button');
      $('#privatemsg-list-form .container-inline .fake-button').removeClass('hide-button');
    }
  });
  
  // same as above but for the select-all checkbox
  $('.select-all .form-checkbox').live('click', function(e) {
    if($('.privatemsg-list input[type="checkbox"]').is(":checked")) {
      /*$('#privatemsg-list-form .container-inline input').css('background-color', '#355274');*/
      $('#privatemsg-list-form .container-inline input').removeClass('hide-button');
      $('#privatemsg-list-form .container-inline .fake-button').addClass('hide-button');
    }
    else {
      /*$('#privatemsg-list-form .container-inline input').css('background-color', '#6e8ba9');*/
      $('#privatemsg-list-form .container-inline input').addClass('hide-button');
      $('#privatemsg-list-form .container-inline .fake-button').removeClass('hide-button');
    }
  });
  
  // submit (via ajax) wall post comment forms when enter key is pressed
  $('.wall-post-first-comment-form textarea, .wall-post-comment-content textarea').live('keydown', function(e) {
    if(e.which == 13 && !e.shiftKey) {
      e.preventDefault();
      if($(this).val() != '') {
        $(this).closest('form').find('input[type="submit"]').mousedown();
      }
    }
  });
  
  // Remove/insert default "Write a comment" text for wall post comments
  $('.wall-post-first-comment-form textarea, .wall-post-comment-content textarea').live('focusin focusout', function(e) {
    switch(e.type) {
      case 'focusin':
        if($(this).val() == 'Write a comment' ) {
          $(this).val('').css('color', 'black');
        }
      break;
      case 'focusout':
        if($(this).val() == '' ) {
          $(this).val('Write a comment').css('color', 'gray');;
        }
      break;
    }
  });
  
  
}(jQuery))
;

