/*
 * jQuery outside events - v1.1 - 3/16/2010
 * http://benalman.com/projects/jquery-outside-events-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// link for all ajax calls, namespaced to help avoid potential collisions
var CustomAjax = {
    ajaxurl: "/wp-admin/admin-ajax.php"
};

(function($,c,b){$.map("click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup".split(" "),function(d){a(d)});a("focusin","focus"+b);a("focusout","blur"+b);$.addOutsideEvent=a;function a(g,e){e=e||g+b;var d=$(),h=g+"."+e+"-special-event";$.event.special[e]={setup:function(){d=d.add(this);if(d.length===1){$(c).bind(h,f)}},teardown:function(){d=d.not(this);if(d.length===0){$(c).unbind(h)}},add:function(i){var j=i.handler;i.handler=function(l,k){l.target=k;j.apply(this,arguments)}}};function f(i){$(d).each(function(){var j=$(this);if(this!==i.target&&!j.has(i.target).length){j.triggerHandler(e,[i.target])}})}}})(jQuery,document,"outside");

/*Basic Accordion Show Hide*/
(function ($) {
		$.fn.basicShowHide = function () {
			$(this).css('cursor', 'pointer')
			$(this).click(function() {
			$(this).toggleClass("accordion-head-active");
			$(this).next().slideToggle('500');
			return false;
		}).next().hide();
	};
})($);

/*Basic Click Dropdown*/
function clickDropdown(element,trigger,expandedTitle,collapsedTitle) {
			//$(element).addClass('collapse');
			$(trigger).click(function() {
				if ($(element).hasClass('expand')) {
						$(element).removeClass('expand');
						$(this).attr('title',collapsedTitle).removeClass('active');
						return false;
				} else {
						$(element).addClass('expand');
						$(this).attr('title',expandedTitle).addClass('active');
						return false;
					};
				});
			$(element).mouseleave(function() {
				$(this).removeClass('expand');
				$(trigger).attr('title',collapsedTitle).removeClass('active');
			});
		}

(function ($) {//function to set heights based on tallest element in the row
			$.fn.equalHeight = function () {
				var tallest = 0;
				$(this).each(function() {
					$(this).css('height','auto');
					var thisHeight = $(this).height();
					if(thisHeight > tallest) {
						tallest = thisHeight;
					}
				});
				$(this).height(tallest);
			};
		})($);

/*sticky panel*/
/*(function (a) { a.fn.stickyPanel = function (c) { var c = a.extend({}, a.fn.stickyPanel.defaults, c); return this.each(function () { a(window).bind("scroll.stickyPanel", { selected: a(this), options: c }, b) }) }; function b(d) { var i = d.data.selected; var g = d.data.options; var l = navigator.userAgent.toLowerCase().indexOf("mobile") > 0; var c = a(window).height(); var e = i.outerHeight(true); var h = a(document).scrollTop(); if (!l && h <= a(document).height() - c && h > i.offset().top - g.topPadding) { var k = 0; if (g.topPadding != "undefined") { k = k + g.topPadding } var p = i.offset().left; i.data("PanelsTop", i.offset().top - k); if (g.savePanelSpace == true) { var n = i.outerWidth(true); var f = i.css("float"); var m = i.css("display"); var j = Math.ceil(Math.random() * 9999); i.data("PanelSpaceID", "stickyPanelSpace" + j); i.before("<div id='" + i.data("PanelSpaceID") + "' style='width:" + n + "px;height:" + e + "px;float:" + f + ";display:" + m + ";'>&nbsp;</div>") } if (g.afterDetachCSSClass != "") { i.addClass(g.afterDetachCSSClass) } i.data("Original_Inline_CSS", (!i.attr("style") ? "" : i.attr("style"))); i.css({ margin: 0, left: p, top: k, position: "fixed" }) } if (h <= i.data("PanelsTop") && i.css("top") != "auto") { if (g.savePanelSpace == true) { a("#" + i.data("PanelSpaceID")).remove() } i.attr("style", i.data("Original_Inline_CSS")); if (g.afterDetachCSSClass != "") { i.removeClass(g.afterDetachCSSClass) } } } a.fn.stickyPanel.defaults = { topPadding: 0, afterDetachCSSClass: "", savePanelSpace: false} })(jQuery);*/



$(document).ready(function(){// JavaScript Document

	var doc_location = document.location.href;
	var next_page = 2;

    $('.module_comments .error').hide();
	/*ADD misc Helper classes*/
	$('table tr').each(function(index) { //give every table column a unique class (per table)
			 $(this).children().each(function(index) {
				$(this).addClass('col' + (index + 1));
			  });
		  });
	$('.common_module_wrap .common_module:last-child, .module_highlighted .common_post:last-child, .module_subtopics ul:last-child, .module_articles .common_post:last, .module_newsletters .common_post:last, .author_box li:last-child, .sponsor_module ul li:last-child, .sidecol .widget:last').addClass('last');
	$('.contact_block:eq(2), .contact_block:eq(3), .contact_block:last, .col_topic:last').addClass('last');

	/*Prepend styled numeric bullets for ordered list*/
	$('.common_ol').each(function(index) { //give every table column a unique class (per table)
			 $(this).children('li').each(function(index) {
				$(this).prepend('<span class="bullet">' + (index + 1) + '</span>');
			  });
		  });
		  
	/*Sticky Panel Ads*/

var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
    var top = $('.widget.last').offset().top - parseFloat($('.widget.last').css('margin-top').replace(/auto/, 0));
    var height = $('.widget.last').outerHeight();
    /*var original_top = $('.widget.last').offset().top;
	var negheight = (-(height)) + (-25) + 'px';
	var before = $('.widget.last').prev();*/
    $(window).bind('scroll resize', function() {
        var y = $(this).scrollTop();
        var z = $('#page_footer').offset().top;
        if (y >= top && (y + height) < z) {
            $('.widget.last').addClass('fixed');
        } else {
            $('.widget.last').removeClass('fixed');
        }
    });
}


	/*Search Box show/hide help text*/
		$('#nav_search .common_search_txt').focus(function() {
			if($(this).val() == "Search SandHill.com"){
			  $(this).attr('value', '');
			}
		});
		$('#nav_search .common_search_txt').blur(function() {
			if($(this).val() == ""){
			  $(this).attr('value', 'Search SandHill.com');
			}
		});

	/*Let's trigger some dropdowns*/
	clickDropdown('.module_topics_dropdown .dropdown', '.module_topics_dropdown h2', 'Collapse', 'Expand' );

	/*Jquery Tabs*/
	$( ".module_common_tabs" ).tabs();

	/* Article Lists */
	$('#btn_more').live('click', function(e) {
		e.preventDefault();

		//jQuery('.more_articles').append('Loading...');

		$.get(doc_location.replace("#", "") + '?list+page=' + next_page, function(data) {
			$('.more_articles').append(data);
			next_page = next_page + 1;


			//are there any more articles
			total_article_count = jQuery('#total_article_count').text();
			current_article_count = jQuery('.related_article').length;


			if (data.length == 0 || current_article_count >= total_article_count) {
				$('#btn_more').hide();
			}

		});

	});

	$('.page-template-template-channel-landing-page-php .excerpt').ThreeDots({ max_rows:10 });
	$('.page-template-template-topic-landing-page-php .excerpt').ThreeDots({ max_rows:11 });
	$('.front-page .excerpt').ThreeDots({ max_rows:7 });
	$('.front-page #tab1 a').ThreeDots({ max_rows:2 });
	
	$('.front-page #tab2').click(function() {
		$('.front-page #tab2 a').ThreeDots({ max_rows:2 });
	});

	/*Mergers and Aquisitions List Modals*/
	$( ".common_modal" ).dialog({
		autoOpen: false,
		show: "fade",
		width: 660,
		modal: true
	});

	/*$( ".module_articles .article_title" ).click(function() {
		$( ".common_modal" ).dialog( "open" );
		//return false;
	}); */
	$('.get_feed').live('click', function(e) {
		e.preventDefault();

		// open modal
		$( ".common_modal" ).dialog( "open" );

		feed_id = ($(this).attr('feed_id'));

		loc = doc_location.replace("#", "");
		loc = loc.substr(0,loc.indexOf("?"))

		$.get(loc + '?feed_id=' + feed_id, function(data) {
			$('.common_modal_replace').html(data);
		});

	});

	$( ".icon_close" ).click(function() {
		$(this).parents('.common_modal').dialog('close');
	});

	/*Search box slide in/out*/
	   if (!$('body').hasClass('home')) {
		  var activeNav = $('#nav_main li.active').width();
		  $('#nav_search').addClass('collapsed');
		  $('#nav_search .common_search_txt').hide();
		  $( ".search_trigger" ).click(function() {
				$(this).hide();
				$("#nav_search").removeClass('collapsed');
				$("#nav_search .common_search_txt").animate({
					'padding-right' : 5,
					'width' : 'toggle',
					'padding-left' : 5
				}, 1000);
				$("#nav_main li.active").animate({width:(activeNav) - 200}, 1000);
			});
	   } else {
		  $('.search_trigger').hide();
	   }

	/*Jquery Validate*/
	$( ".frm_comment_success" ).dialog({
		autoOpen: false,
		show: "fade",
		width: 435,
		modal: true
	});

    $('#trigger_new_comment').click(function(e){
        //take over link clink
        e.preventDefault();
        //clear comment textarea to prep for new comment
        $('textarea[name="comment"]').val('');
        //display the hidden comment form
        $('#frm_comment').show();
        // hide any errors for a new try
        $('.error').hide();
        //hide this new comment link trigger
        $(this).hide();
    });

    /* Same as above just on the ID rather than the class... specifying form id is easy in Wordpress but not form class */
    $("#frm_comment").validate({
        errorContainer: ".error_general",
        rules: {
            email: {
                email: true
            },
            author: {
                required: true
            },
            comment: {
                required: true
            }
        },
        submitHandler: function(data) {
            $('#frm_comment').hide();
            $('#spinner').show();
            $.ajax({
                type: "POST",
                url: "/wp-comments-post.php",
                data: $(data).serialize(),
                success: function() {
                    $(".frm_comment_success").dialog("open");
                },
                error: function(xhr) {
                    $('#spinner').hide();
                    $('#frm_comment').show();
                    console.log(xhr.status);
                    $('.error').text('There was an error submitting your comment. Please try again later.').show();
                },
                complete: function() {
                    $('#spinner').hide();
                    $('#trigger_new_comment').show();
                }
            });
        }
    });
	$( ".frm_comment_success .common_btn, .frm_comment_success .icon_close" ).click(function() {
		$(".frm_comment_success").dialog('close');
		return false;
	});

	/*contact form*/
	$("#contact_frm").validate({
        submitHandler: function(data){
				$('#contact_frm .spinner').show();

            	var first_name = $("input#first_name").val();
				var last_name = $("input#last_name").val();
				var company = $("input#company").val();
				var title = $("input#title").val();
				var email = $("input#email").val();
				var message = $("textarea#message").val();
				var subject = $("input#subject").val();
				var dataString = 'first_name='+ first_name + '&last_name=' + last_name + '&company=' + company + '&title=' + title + '&email=' + email + '&message=' + message + '&subject=' + subject;

				$.ajax({
				  type: "POST",
				  url: "/wp-content/themes/sandhill/ajax-email.php",
				  data: dataString,
				  success: function() {
					$('#contact_frm').fadeOut(1000);
					$('#success_message').fadeIn(1000);
					$('#contact_frm .spinner').fadeOut(1000);
				  },
                error: function() {
					$('#error_message').fadeIn(1000);
					$('#contact_frm .spinner').hide();
				 },
			 });
        },
	   errorContainer: "#missing_fields",
	   rules: {
		 email: {
		   email: true
		 }
	   }
	});

    /* Newsletter signup submit handler */
    $("#ccsfg").submit(function(e){
        $('#signup_submit').hide();
        $('#spinner').show();
        e.preventDefault();
		
		/* Action is a hooks in functions.php in the theme
		* wp_ajax_nopriv_newsletter-subscribe
		* wp_ajax_newsletter-subscribe
		//These hooks call a function called newsletter_subscribe
        */
		var data = "action=newsletter-subscribe&nonce=" + $('#newsletter-nonce').val() + "&FirstName=" + $("#FirstName").val() + "&LastName=" + $("#LastName").val() + "&CompanyName=" + $("#CompanyName").val() + "&JobTitle=" + $("#JobTitle").val() + "&EmailAddress=" + $("#EmailAddress").val();
        $.post('/wp-admin/admin-ajax.php', data, function( data, textStatus, jqXHR ) {
            $('#signup_submit').show();
            $('#spinner').hide();
            $('#subscribe_message').html(data).show();
        });
    });

	/* View More in sidebar */
	$( ".view_more_action" ).click( function(e) {
		e.preventDefault();
		$( ".view_more_item" ).show();
		$( ".view_more_action" ).hide();
	});

	/*On Mergers & Aquisitions and Venture Capital Deals home page modules, set height to whichever is tallest*/
	$('.home .common_module_wrap .common_module').equalHeight();

	// THEME SWITCHER
	$(".switcher").click( function(event) {
		event.preventDefault();
		lb_viewport = $(this).attr('version');
		$.ajax({
			type: "POST",
			url: "/ajax-theme-switcher/",
			data: "lb_viewport=" + lb_viewport,
			success: function(html){
				location.reload();
			}
		});
		
		//location.reload();

	});

	// ADD THIS
	// Callback for when the user shares an item - this should be an ajax function
	function addthisShare(evt) {
		// send AJAX to WP plugin that will update the ID in the database with a new field - "shared"
		$.post('/wp-admin/admin-ajax.php',
				{ action : 'increment_shares',
					post_id : post_id
				},
				function (response) {
				}
		);

	} // End Callback

	// Listen for the ready event and set callback
	if (typeof addthis != 'undefined') {
		addthis.addEventListener('addthis.menu.share', addthisShare);
	}
});
