/* Helpers */

	var fullWidth;
	var fullHeight;
	var scrollX;
	var scrollY;
	var mH = 0;		// Invisible element height
	var t;
	var tooltipped = 0;

$(document).ready(function(){		
	
	//######################################
	//## Font size cookie saving stuff ####
	//####################################
	var COOKIE_NAME = 'test_cookie';
 	var fontCookie = $.cookie(COOKIE_NAME);
	var options = { path: '/', expires: 1 };
	
	$('#textSizer a').live("click", function(){
		$(this).removeClass('on');
		var fontId = $(this).attr('class');
		$.cookie(COOKIE_NAME, fontId, options);
		
		var fontCookie = $.cookie(COOKIE_NAME);
		if($.cookie(COOKIE_NAME)==$.cookie(COOKIE_NAME)){
			$('#textSizer a').removeClass('on');
			$(this).addClass('on');
			$('body').removeClass('larger');
			$('body').removeClass('largest');
			if (fontCookie=='larger'||fontCookie=='largest') {
				$('body').addClass(fontCookie);
			}
		}
	    return false;
	});
 	

	if (fontCookie=='larger'||fontCookie=='largest') {
 		$('#textSizer a').removeClass('on');
 		$('#textSizer a.'+fontCookie).addClass('on');
		$('body').removeClass('larger');
		$('body').removeClass('largest');
 		$('body').addClass(fontCookie);
	}
	// End cookies
	//###########
	
	$('.event-back').click(function(){
		// history.go(-1);
		// return false;
	})
	
	$('#articleMain.event .article-head p.date').changeDate();
	$('#featureBox div ol li p.date.event-date').changeDate();
	$('#calendarList ul li p.date').each(function(){
		$(this).changeDate();
		
		//oldDate = oldDate+' 00:00:00.000';
		//console.log($(this).html());
		//var newDate = $.format.date(oldDate, "dd/MM/yyyy");
		//$(this).html(newDate);
		//console.log(newDate);
	});
	
	Date.format = 'mm/dd/yyyy';
	$('#byDate.filter dd table .text-input input#startDate').datePicker({clickInput:true, createButton:false});
	$('#byDate.filter dd table .text-input input#endDate').datePicker({clickInput:true, createButton:false});
	
					   
	fullWidth = $(window).width();
	fullHeight = $(window).height();
	scrollX = $(window).scrollLeft();
	scrollY = $(window).scrollTop();
	
	$('#siteNav dd ul li a.on').closest('li').prev().children('a').addClass('prev');
	$('#tooltip a').append('<span class="arrow">&nbsp;&nbsp;&#9658;</span>');
	$('#content .close').prepend('<span class="arrow">x &nbsp;</span>');

	$('.btn, .btn2, .btn3').each(function(){
		$(this).wrapInner('<span class="text" />');
		$(this).prepend('<span class="left"></span><span class="right"></span>');
		if ($(this).hasClass('prev')) {
			$('span.text',this).prepend('<span class="arrow">&#9668;&nbsp;&nbsp;</span>');
		}
		if ($(this).hasClass('next')) {
			$('span.text',this).append('<span class="arrow">&nbsp;&nbsp;&#9658;</span>');
		}
	})
	
	$('#arms .list li').each(function(){
		$(this).addClass('item'+( parseInt($("#arms .list ol li").index(this))+1));
	});
	
	$('#featureBox.random div ol').each(function(){
		var w = $('#featureBox.random div ol li').length; 
		var r = Math.floor(Math.random()*w);
		$('li',this).eq(r).addClass('on');
	})
	
	$('#featureBox.slide-show div ol').each(function(){
		var w = ( $('#featureBox.slide-show div ol li').length + 1) * 945;
		$('#featureBox.slide-show div ol').width(w);
		setTimeout(function(){
			slideshow()
		},6500)
	});
	
	$('#featureBox.slide-show dl dd ol li').each(function(){
		$('#featureBox.slide-show dl dd ol li:first-child').addClass('on');
		var p = parseInt($("#featureBox.slide-show dl dd ol li").index(this))+1;
		$(this).prepend('<span>'+p+'</span>');
		var q = $('#featureBox.slide-show dl dd ol li').index(this);
		$(this).click(function(){
			$('#featureBox.slide-show div ol').stop();
			clearTimeout(t);
			var r = $('#featureBox.slide-show div ol li').eq(q).position(); 
			$('#featureBox.slide-show div ol').animate({
				'left' : 55-(r.left)
			},2000,function(){
				$('#featureBox.slide-show dl dd ol li').removeClass('on');
				$('#featureBox.slide-show dl dd ol li').eq(q).addClass('on');
			});
			return false;
		})
	});

	$('#featureBox.slide-show div ol li').each(function(){
		var num = parseInt($("#featureBox.slide-show div ol li").index(this))+1;
		$(this).attr('id','num'+num);
	});
	
	$('form input[type="text"], form input[type="password"]').focus(function() {
			if( $(this).val() == this.defaultValue ) {
				$(this).attr("value", "");
			}
		}).blur(function() {
			if( !$(this).val().length ) {
				$(this).attr("value", this.defaultValue);
			}
	});
	
	$('input[type="text"], input[type="password"]').addClass('text');

	$('#eventSort td.checkbox').click(function(){
		if ($('input:checked', this).val() !== null) {
			$(this).parent('tr').toggleClass('on');
		}
	});
	
	$('#eventSort td.checkbox input:checked').each(function(){
		$(this).closest('tr').addClass('on');
	})
	
	$('#byType p a.all, #byLocation p a.all').click(function(){
		var w = $(this).closest('div.filter');
		w.find('tr').addClass('on');
		w.find('input:checkbox').attr('checked','checked');
		return false;
	});
	
	$('#byType p a.none, #byLocation p a.none').click(function(){
		var w = $(this).closest('div.filter');
		w.find('tr').removeClass('on');
		w.find('input:checkbox').attr('checked','');
		return false;
	});
	
	$('#arms #shareTips').click(function(){
		location.href = "/tips/";
	});
	
	$(".filter input#type-all-massachusetts").click(function(){
        var checked = $(this);
        $(".filter input[name='areas[]']").each(function(){
            var locID = $(this).attr('id');
            if(checked.attr('checked'))
			{
                if(locID.indexOf('-ma') != -1){
                    $(this).attr('checked','checked');
                    $(this).closest('tr').addClass('on');
                }
            }
            else
			{
                if(locID.indexOf('-ma') != -1)
				{
                    $(this).removeAttr('checked');
                    $(this).closest('tr').removeClass('on');
                }
            }

        });
    });
 
	
	/*
	$('#textSizer a').click(function(){$('#textSizer a').removeClass('on');$(this).addClass('on');});
	$('#textSizer a.default').click(function(){$('body').removeClass('larger').removeClass('largest');return false;});
	$('#textSizer a.larger').click(function(){$('body').addClass('larger').removeClass('largest');return false;});
	$('#textSizer a.largest').click(function(){$('body').addClass('largest').removeClass('larger');return false;});
	*/
	
	$('#top5 dd ul li a').each(function(){
		var alphabet = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
		var first = $(this).text().charAt(0).toLowerCase();
		var which = alphabet.indexOf(first);
		if ( which < 6 ) {
			$(this).attr('href','/glossary/#a');
		} else if ( which >= 6 && which < 12 ) {
			$(this).attr('href','/glossary/#g');
		} else if ( which >= 12 && which < 19 ) {
			$(this).attr('href','/glossary/#m');
		} else {
			$(this).attr('href','/glossary/#t');
		} 
	});
	
	$('.home #calendarList ul li:last-child, #articleMain.coupons ul li:last-child, #shareTip1 form table .radios td:last-child').addClass('last');
		
	$('#articleList ul, #videoList ul').each(function(){
		//$('li',this).equalize();
		$(this).find('li:even').addClass('even');
	});
	
	$('#shareTips blockquote').prepend('<span class="open"></span>').append('<span class="close"></span>');
	
	//$('#placeholder').live('click',function(){alert('hi mark');});
	
	//## Open Modal
	$('.launch-modal').click(function(){
		which = $(this).attr('href');
		post_id = $(this).attr('id').split("-")[1];
		openModal(which, post_id);
		return false;
	});
	
	//## Next Modal
	//$('.modal button').click(function(){
	//	nextStep($(this));
	//	return false;
	//});

	//## Close Modal with buttons
	$('.close-modal, .modal .cancel').click(function(){
		$('#modals').fadeOut('slow',function(){
			$('html').css({'overflow':'auto'});
			$('div.modal').css({'display' : 'none'});
		});
		return false;
	});
	
	//## Close modal by clicking off
	$('#modals').click(function(e){
		if ( $(e.target).attr('id') == "modals" ) {
			$('#modals').fadeOut('slow',function(){
				$('html').css({'overflow':'auto'});
				$('div.modal').css({'display' : 'none'});
			});
		} else return; 
	});

	$('.tooltip').click(function(e){
		tooltipped = 1; 
		var guts = $(this).attr('href');
		var post = guts.split('#');		
		var data = {
        	action: 'mrh_fetch_glossary_term',
        	slug: post[1]
    	};
    	
    	jQuery.post(ajaxurl, data, function(response) {
            var ar=response.split("*");            
                $('div#tooltip p').html(ar[1]);

			$('div#tooltip p').truncate({
				charNum : 130
			});
               $('div#tooltip a').attr("href",$('div#tooltip a').attr("href")+'/#'+ar[0]);
                       
    		$('div#tooltip').css({
    			'top' : e.pageY-($('div#tooltip').height()+30),
    			'left' : e.pageX-30
    		}).toggle();
    	});
	    return false;
	});
	
	$('#tooltip').click(function(){
		$(this).hide();
	});

	//## Close tooltip by clicking off
	$('body').click(function(e){
		if ( $(e.target).attr('id') != "tooltip" ) {
			$('#tooltip').hide();
		} else return; 
	});
	
	$('td a.info').click(function(e){
		var link = "/legal-privacy-and-security";
		$('div#tooltip p').remove();
		$('div#tooltip a:not(.close)').attr('href',link).html('View full privacy policy').show();
		$('div#tooltip').css({
			'top' : e.pageY-($('div#tooltip').height()+30),
			'left' : e.pageX-30
		}).toggle();
		return false;
	});
	
	$('#comments').each(function(){
		if ($('#comments ol li').length < 5 ) {
			$('#comments p.show-comments').hide();
		} else {
			$('li', this).filter(function(index) {
			  return index > 4;
			}).hide();
		}
	});
	
	$('#comments p.show-comments a').toggle(function(){
		$('#comments ol li').show();
		$(this).removeClass('show').addClass('hide');
		return false;
	}, function(){
		$('#comments ol li').filter(function(index) {
		  return index > 4;
		}).hide();
		$(this).removeClass('hide').addClass('show');
		return false;
	});
	
	/* Sharing is caring */
	
	$('.share a').each(function(){
		var url = location.href;
		var title = document.title; 
		$(this).attr('target','_blank');
		if ( $(this).hasClass('facebook')) {
			$(this).attr('href','http://www.facebook.com/sharer.php?u='+url+'&t='+title)
		} else if ( $(this).hasClass('delicious') ) {
			$(this).attr('href','http://del.icio.us/post?url='+url+'&title='+title);
		} else if ( $(this).hasClass('digg') ) {
			$(this).attr('href','http://digg.com/submit?phase=2&url='+url+'&title='+title);
		} else if ( $(this).hasClass('twitter') ) {
			$(this).attr('href','http://twitter.com/home?status='+url);
		}
	});
	
	doTipsStuff();
	
	$("a.print").attr( "href", "javascript:void( 0 )" ).click(     
           function(){
                    // Print the DIV.
		$( "#articleMain" ).prints();
		 // Cancel click event.
		return( false );
               }

    );
	
	// Mark's Ajax Fun Zone
	
    doRatingStuff();
	
	$("#newsletter1 button").click(function() {
	    var data = {
        	action: 'mrh_imn_submit',
        	email: $("#newsletter1").find("#newsEmail").val(),
        	type: "Add"
    	};
    	
	    jQuery.post(ajaxurl, data, function(response) { 
            nextStep($("#newsletter1 button"));
	    }); 
	    return false;
	});
	
	$("#coupon2 button").click(function() {
	    window.print();
	    nextStep($(this));
	    return false;
	});
	
	$("form#comment button").click(function() {
				var comEmail=$("#commentEmail");
				var comName=$("#commentName");
				var comText=$("#commentText");
				var comCheck=$("#gasp_checkbox");
				
		//validate name
		if(comName.val()=="Your Name"|| jQuery.trim(comName.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			comName.focus();
			return false;			
		}else{
				if(/[^a-zA-Z\s.]/.test(comName.val())){
				alert("Name should have alphabates.");
				comName.focus();
				return false;			
			   }
		}	
		//validate email 
		if(comEmail.val()=="you@yours.com"|| jQuery.trim(comEmail.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			comEmail.focus();
			return false;
		}else{
				if(!isEmail(comEmail.val())){
				alert("Please Enter a valid email.");
				comEmail.focus();
				return false;			
			   }
		}
		//validate comment 
		if(jQuery.trim(comText.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			comText.focus();
			return false;
		}
		//add check if checked here.
		if(!comCheck.attr('checked')){
			//console.log(comCheck.val());
			alert("Please confirm that you are not a spammer.");
			comCheck.focus();
			return false;
		}
		
		openModal('#commented');
		
	    var data = {
        	action: 'mrh_csv_submit',
        	email: $("form#comment").find("#commentEmail").val(),
        	name: $("form#comment").find("#commentName").val()
    	};
		
		$('#commented a.close-modal').click(function(){
	    	jQuery.post(ajaxurl, data, function(response) { 
	    	    $("form#comment").submit();
	    	});
			return false;
		})
    	
    	return false;
	});
	
	$("#shareTip1 button").click(function() {
										  
		var tip = $('#tipText').val();
		var charNum = tip.length;
		
		var shareEmail=$("#couponEmail");
		var shareName=$("#couponName");
		var shareText=$("#tipText");		
					
		//validate name
		if(shareName.val()=="Your Name"|| jQuery.trim(shareName.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			shareName.focus();
			return false;			
		}else{
				if(/[^a-zA-Z\s.]/.test(shareName.val())){
				alert("Name should have alphabates.");
				shareName.focus();
				return false;			
			   }
		}	
		//validate email 
		if(shareEmail.val()=="you@yours.com"|| jQuery.trim(shareEmail.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			shareEmail.focus();
			return false;
		}else{
				if(!isEmail(shareEmail.val())){
				alert("Please Enter a valid email.");
				shareEmail.focus();
				return false;			
			   }
		}
		//validate comment 
		if(shareText.val()=="Enter your tip here." ||jQuery.trim(shareText.val())==""){			
			alert("Please fill in all form fields before clicking submit.");
			//comText.html("");
			shareText.focus();			
			return false;
		}
		
		if (charNum > 210) {
			alert('Your tip must be less than 210 characters long!');
			return false;
		}
		
	    var data = {
        	action: 'mrh_tip_submit',
        	email: $("#shareTip1").find("#couponEmail").val(),
        	name: $("#shareTip1").find("#couponName").val(),
        	text: $("#shareTip1").find("#tipText").val(),
        	cat: $("#shareTip1").find("input[@name='tipCategory']:checked").val()
    	};
    	
    	jQuery.post(ajaxurl, data, function(response) {
    	    $("#shareTip1").find("input").each(function() {
        	    this.value = this.defaultValue;
        	});
        	$("#shareTip1").find("textarea").each(function() {
        	    this.value = this.defaultValue;
        	});
    	});
    	
    	var data = {
    	    action: 'mrh_csv_submit',
        	email: $("#shareTip1").find("#couponEmail").val(),
        	name: $("#shareTip1").find("#couponName").val()
    	}
        jQuery.post(ajaxurl, data, function(response) { 
            nextStep($("#shareTip1 button"));
        });
    	return false;
	});
	
	$("#tellFriend1 button").click(function() {
		var articleEmail=$("#tellFriendEmail");
		var articleName=$("#tellFriendName");
		var tellFriendName=$("#friendName");
		var tellFriendEmail=$("#friendEmail");
		var articleText=$("#message");		
					
		//validate name
		if(articleName.val()=="Your Name"|| jQuery.trim(articleName.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			articleName.focus();
			return false;			
		}else{
				if(/[^a-zA-Z\s.]/.test(articleName.val())){
				alert("Name should have alphabates.");
				articleName.focus();
				return false;			
			   }
		}	
		//validate email 
		if(articleEmail.val()=="you@yours.com"|| jQuery.trim(articleEmail.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			articleEmail.focus();
			return false;
		}else{
				if(!isEmail(articleEmail.val())){
				alert("Please Enter a valid email.");
				articleEmail.focus();
				return false;			
			   }
		}
		//validate name
		if(tellFriendName.val()=="Your Name"|| jQuery.trim(tellFriendName.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			tellFriendName.focus();
			return false;			
		}else{
				if(/[^a-zA-Z\s.]/.test(tellFriendName.val())){
				alert("Name should have alphabates.");
				tellFriendName.focus();
				return false;			
			   }
		}	
		//validate email 
		if(tellFriendEmail.val()=="you@yours.com"|| jQuery.trim(tellFriendEmail.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			tellFriendEmail.focus();
			return false;
		}else{
				if(!isEmail(articleEmail.val())){
				alert("Please Enter a valid email.");
				articleEmail.focus();
				return false;			
			   }
		}
		//validate comment 
		if(articleText.val()==" " ||jQuery.trim(articleText.val())==""){			
			alert("Please fill in all form fields before clicking submit.");
			//comText.html("");
			articleText.focus();			
			return false;
		}
		
	    var data = {
        	action: 'mrh_tell_friend_submit',
        	email: $("#tellFriend1").find("#tellFriendEmail").val(),
        	name: $("#tellFriend1").find("#tellFriendName").val(),
        	friend_name: $("#tellFriend1").find("#friendName").val(),
        	friend_email: $("#tellFriend1").find("#friendEmail").val(),
        	message: $("#tellFriend1").find("#message").val(),
        	url: window.location.href.split("?")[0]
    	};
    	
    	jQuery.post(ajaxurl, data, function(response) {
    	   
    	});
    	
    	var data = {
    	    action: 'mrh_csv_submit',
        	email: $("#tellFriend1").find("#tellFriendEmail").val(),
        	name: $("#tellFriend1").find("#tellFriendName").val()
    	}
        jQuery.post(ajaxurl, data, function(response) { 
            nextStep($("#tellFriend1 button"));
        });
    	return false;
	});
	
	$("#suggestEvent1 button").click(function() {
											  
		var eventEmail=$("#eventEmail");
		var eventName=$("#eventName");
		var eventTitle=$("#eventTitle");
		var eventDescription=$("#eventText");
					
		//validate name
		if(eventName.val()=="Your Name"|| jQuery.trim(eventName.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			eventName.focus();
			return false;			
		}else{
				if(/[^a-zA-Z\s.]/.test(eventName.val())){
				alert("Name should have alphabates.");
				eventName.focus();
				return false;			
			   }
		}	
		//validate email 
		if(eventEmail.val()=="you@yours.com"|| jQuery.trim(eventEmail.val())==""){
			alert("Please fill in all form fields before clicking submit.");
			eventEmail.focus();
			return false;
		}else{
				if(!isEmail(eventEmail.val())){
				alert("Please Enter a valid email.");
				eventEmail.focus();
				return false;			
			   }
		}
		//validate comment 
		if(eventTitle.val()=="Enter your event title here." ||jQuery.trim(eventTitle.val())==""){			
			alert("Please fill in all form fields before clicking submit.");
			//comText.html("");
			eventTitle.focus();			
			return false;
		}
		if(eventDescription.val()=="Enter your event, along with location, date, time and any other details specific to the event here." ||jQuery.trim(eventDescription.val())==""){			
			alert("Please fill in all form fields before clicking submit.");
			eventDescription.html("");
			eventDescription.focus();			
			return false;
		}
											  
	    var data = {
        	action: 'mrh_event_submit',
        	email: $("#suggestEvent1").find("#eventEmail").val(),
        	name: $("#suggestEvent1").find("#eventName").val(),
        	title: $("#suggestEvent1").find("#eventTitle").val(),
        	text: $("#suggestEvent1").find("#eventText").val(),
            cat: $("#suggestEvent1").find("input:radio:checked").val()
    	};
    	jQuery.post(ajaxurl, data, function(response) { });
    	
    	var data = {
    	    action: 'mrh_csv_submit',
        	email: $("#suggestEvent1").find("#eventEmail").val(),
        	name: $("#suggestEvent1").find("#eventName").val()
    	}
        jQuery.post(ajaxurl, data, function(response) { 
            $("#suggestEvent1").find("input").each(function() {
        	    this.value = this.defaultValue;
        	});
            nextStep($("#suggestEvent1 button"));
        });
    	
    	return false;
	});
	
	$("#coupon1 button").click(function() {
		
		if ( $("#couponName").val() == 'Your Name' ) {
			alert('Please enter your name.');
			return false;
		}
		
		if ( $("#couponEmail").val() == 'you@yours.com' ) {
			alert('Please enter your email address.');
			return false;
		}
		
	    var data = {
        	action: 'mrh_csv_submit',
        	email: $("#coupon1").find("#couponEmail").val(),
        	name: $("#coupon1").find("#couponName").val(),
        	post_id: $("#coupon1").find("#couponPostId").val()
    	};

	   jQuery.getJSON(ajaxurl, data, function(response) { 
	       if(response != false) {
	           $("#coupon2").find("#coupon-content").html("");
               $("#coupon2").find("#coupon-content").append('<p>' + response.post_thumbnail + '</p>');
	           $("#coupon2").find("#coupon-content").append('<h3>' + response.post_title + '</h3>');
	           $("#coupon2").find("#coupon-content").append('<p>' + response.post_content + '</p>');
	           
	           nextStep($("#coupon1 button"));
	       } else {
	           $('#modals').fadeOut('slow',function(){
       			   $('html').css({'overflow':'auto'});
       			   $('div.modal').css({'display' : 'none'});
       		   });
       		   return false;
	       }
	   });
	   return false;
	});
	
	$('#coupon1 input').keypress(function(event) {
	  if (event.keyCode == '13') {
	     if ( $("#couponName").val() == 'Your Name' ) {
			alert('Please enter your name.');
			return false;
		}

		if ( $("#couponEmail").val() == 'you@yours.com' ) {
			alert('Please enter your email address.');
			return false;
		}

	    var data = {
        	action: 'mrh_csv_submit',
        	email: $("#coupon1").find("#couponEmail").val(),
        	name: $("#coupon1").find("#couponName").val(),
        	post_id: $("#coupon1").find("#couponPostId").val()
    	};

	   jQuery.getJSON(ajaxurl, data, function(response) { 
	       if(response != false) {
	           $("#coupon2").find("#coupon-content").html("");
               $("#coupon2").find("#coupon-content").append('<p>' + response.post_thumbnail + '</p>');
	           $("#coupon2").find("#coupon-content").append('<h3>' + response.post_title + '</h3>');
	           $("#coupon2").find("#coupon-content").append('<p>' + response.post_content + '</p>');

	           nextStep($("#coupon1 button"));
	       } else {
	           $('#modals').fadeOut('slow',function(){
       			   $('html').css({'overflow':'auto'});
       			   $('div.modal').css({'display' : 'none'});
       		   });
       		   return false;
	       }
	   });
	   return false;
	   }
	});
	
	
	$("#byLocation.filter input[name='all-massachusetts']").click(function(){
		if($(this).attr('checked')){
			
		}
		var checked = $(this);
		$("#byLocation.filter input[name='typeFilter[]']").each(function(){
			var locID = $(this).attr('id');
			var paged = parseInt($("#pageNumber").html());
			
			if(checked.attr('checked')){
				if(locID.indexOf('-ma') != -1){
					$(this).attr('checked','checked');
					$(this).closest('tr').addClass('on');
					isChecked();
				}
			}
			else{
				
				if(locID.indexOf('-ma') != -1){
					$(this).attr('checked','');
					$(this).closest('tr').removeClass('on');
					isChecked();
				}
			}

		});
	});
	
	
	$('.button-filter-update, #updateDateFilter').click(function() {
		$('#eventSort').submit();
	});

	$('form#eventSort').submit(function() 
		{
			var values = []

	        values['types'] = [];
	        $('input[name^=types]:checkbox:checked').each(function() {
	                values['types'].push($(this).val());
	        });

	        values['areas'] = [];
			if ($('input[name^=areas]:checkbox:checked').length > 0) 
			{
				$('input[name^=areas]:checkbox:not(:checked)').each(function() {
		                values['areas'].push($(this).val());
		        });
			}
			
		    $('form#eventSort input:[name=type]:hidden').val(values['types'].join(','));
	        $('form#eventSort input:[name=area]:hidden').val(values['areas'].join(','));
		}
	);
	
	
	$("#moreTips").click(function() {
	    var listSize = $("#tipList li").size();
		var pagenum=parseInt($("#pgNum").html());
		var showPosts=$("#showposts").html()
	    var data = {
        	action: 'mrh_retrieve_tips',
        	num: pagenum+1,
			showPosts:showPosts
    	}; 
		/*if(listSize<12){
			 $("#moreTips").hide();
			 return false;
		}
            */
    	jQuery.getJSON(ajaxurl, data, function(response) { 
    	    var tipHtml = $("#tipList li:first");

    	    $("#tipList").html("");
    	    
    	    for(var tip in response.tips_results) {	
				var tipTruncate = response.tips_results[tip].content;
				var pageUrl = document.location.href;
//				console.log(tipTruncate);
				//tipTruncate.truncate({ charNum : 46 });
//				tipTruncate = tipTruncate.truncateText(46);
				tipTruncate = tipTruncate.substr(0,46);
				tipTruncate = tipTruncate + '... ';
				//tipTruncate = tipTruncate + pageUrl;
				tipTruncate = tipTruncate + response.tips_results[tip].url;
				//console.log(response.tips_results[tip]);
                newTip = tipHtml.clone();
                newTip.attr("class", "off " + response.tips_results[tip].cat);
				newTip.attr("id", "tip-" + response.tips_results[tip].the_id);
                newTip.find("blockquote").html(response.tips_results[tip].content);
    	        newTip.find(".who").html("- " + response.tips_results[tip].tip_author);
                newTip.find(".perc").html(response.tips_results[tip].rating);
                newTip.find(".metadata").html(response.tips_results[tip].the_id);    	        
    	        $("#tipList").append(newTip);
				newTip.find('.twitter').attr('href', 'http://twitter.com/home/?status='+tipTruncate);
    	    }  
			 if(response.total_pages > 0) {
				 //to update the pagenumber by raju kumar intelegencia
				  $("#pgNum").html(response.page_num);
			 }
			 if(response.page_num == response.total_pages) {
				 //to hide the more tips buttons with last post and scrol to top  by raju kumar intelegencia
				       // $('html, body').animate({scrollTop:0}, 700);
        	            $("#moreTips").hide();
        	 }
                 if(response.page_num > 0)
			 {
			  	$('html, body').animate({scrollTop:(response.page_num*420)}, 700);
			 }
    	    doTipsStuff();
    	    doRatingStuff();    	    
        });
        
        return false;
	});
	
	
	$('#clearDates').click(reset_date_filters);
	
	/* Windows Chrome? I wish this was a joke. */
		
		browser = navigator.userAgent.indexOf('Chrome');
		os = navigator.userAgent.indexOf('Win');
		if ( (browser != -1) && (os != -1) ) {$('body').addClass('chrome');}
	
});

var reset_date_filters = function() {
	var d = new Date();
	var today = (d.getMonth()+1) + '/' + d.getDate() + '/' + d.getFullYear();
	$('#eventSort input:text[name=date_start]').val(today);
	$('#eventSort input:text[name=date_end]').val('mm/dd/yy');
	
	return false;
}

$(window).resize(function(){

	fullWidth = $(window).width();
	fullHeight = $(window).height();
	scrollX = $(window).scrollLeft();
	scrollY = $(window).scrollTop();

	$('.modal:visible').each(function(){
		$(this).css({
			'margin-top' : scrollY + ((fullHeight - (mH+100))/2)
		});
	});
	$('#modals').css({
		'height' : fullHeight,
		'width' : fullWidth
	});
});

function doRatingStuff() {
    $('.rating a').click(function(){
		var parent = $(this).closest('.rating');
		$('a',parent).removeClass('on');
		$(this).addClass('on');
		var which = $(this).offset();
		$('<span id="thanks"></span>').appendTo('body').css({
			'top' : which.top-40,
			'left' : which.left-16
		}).animate({
			height: 51,
			width: 81
		}, 250, function(){
			setTimeout(function(){
				$('#thanks').animate({
					height: 0,
					width: 0
				}, 250, function(){
					$(this).remove();
				});
			},1000);
		})
		return false;
	});
	
    $(".rating .up, .rating .down").click(function() {
        var data = {
        	action: 'mrh_rate',
        	post_id: $(this).siblings(".metadata").html(),
    	    dir: $(this).attr("class").search("up") ? "down" : "up"
    	};

    	// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    	jQuery.post(ajaxurl, data, function(response) { });
    });    
}

function doTipsStuff() {
    
	$('#tipList li:nth-child(3n)').addClass('col3');
	$("#tipList li:gt("+($("#tipList li").length-4)+")").addClass("last");

	
	$('#tipList li blockquote').truncate();
	
	$('#tipList li').each(function(){
		if ( $(this).is(':first-child') ) {var p = 'first'}
			else {var p = $(this).prev().attr('id');}
		if ( $(this).is(':last-child') ) {var n = "last"}
			else {var n = $(this).next().attr('id');}
		$(this).find('a.prev').attr('href','#'+p);
		$(this).find('a.next').attr('href','#'+n);
	});
	
	$('#tipList li').click(function(){
		var h = $(this).height();
		if ($(this).hasClass('on')) {
			//return false;
		} else {
			$('li#placeholder').remove();
			$('#tipList li.on').css({
				width: 253,
				height: h
			}).removeClass('on');
			var z = $(this);
			var p = z.position();
			if (z.hasClass('col3')) { // Special case for right-alignment
				z.css({
					right: '25px'
				});
			}
			else {
				z.css('left', p.left)
			}
			if (z.hasClass('last')) { // Special case for bottom alignment
				z.css({
					bottom: '72px'
				});
			}
			else {
				z.css('top', p.top)
			}
			if (z.hasClass('col3')) {
				z.after('<li id="placeholder" class="col3"></li>');
			}
			else {
				z.before('<li id="placeholder"></li>');
			}
			z.addClass('on');
			z.animate({
				width: 575,
				height: 203
			});
		}
	});
	
	$('#tipList li a.close').click(function(){
		$(this).closest('li').animate({
			width: 253,
			height: 74
		}, function(){
			$(this).removeClass('on');
			$('li#placeholder').remove();
		});
		return false;
	});
	
	$('#tipList li a.next, #tipList li a.prev').click(function(){
		var w = $(this).attr('href');
		if ( w == "#first" || w == "#last") {
			$('#tipList li.on').animate({
				width: 253,
				height: 74
			}, function(){
				$('li#placeholder').remove();
				$(this).removeClass('on');
			});
			return false;
		} else {
			$('li' + w).click();
			return false;
		}
	});
}

function openModal(which, id){
    if(!id) {id = null;}
    
	var w = $(which);
	$('div.modal-wrap',which).findHeight();
	$('html').css({'overflow':'hidden'});
	fullWidth = $(window).width();
	fullHeight = $(window).height();
	scrollX = $(window).scrollLeft();
	scrollY = $(window).scrollTop();
	w.css({
		'margin-top' : (fullHeight-(mH+100))/2,
		'display' : 'inline-block'
	});
	if(id) { 
	    w.find("#couponPostId").attr("value", id);
	}
	$('#modals').css({
		'top' : scrollY,
		'left' : scrollX,
		'height' : fullHeight,
		'width' : fullWidth
	}).fadeIn('slow');		
}

function nextStep(w) {
	var guy = w.parents('div.modal');
	var nextGuy = guy.next('div.modal');
	nextGuy.findHeight();
	guy.fadeOut('slow',function(){
		nextGuy.css({
			'margin-top' : (fullHeight-(mH+100))/2,
			'display' : 'inline-block',
			'opacity' : 0
		}).animate({
			'opacity' : 1
		},"slow");
	});
	$("#tooltip").hide();
}

function slideshow(){
	var y = $('#featureBox.slide-show div ol').position();
	if (y.left >= (0 - ($('#featureBox.slide-show div ol li').length-1) * 945)) {
		var a = y.left - 946
	} else {var a = 0}
	$('#featureBox.slide-show div ol').animate({
		'left': a
	},1500,function(){
		$('#featureBox.slide-show dl dd ol li').removeClass('on');
		if ( (0-(y.left/946)) < 4) {
			$('#featureBox.slide-show dl dd ol li').eq((0-(y.left/946))+1).addClass('on');
		} else {
			$('#featureBox.slide-show dl dd ol li').eq(0).addClass('on');
		}
		t = setTimeout(function(){
			slideshow()
		},6500)
	});

}

jQuery.fn.findHeight = function(){
	
	return $(this).each(function() {
		$('#newGuy').remove();
		$(this).clone(true)
			.attr('id','newGuy')
			.appendTo('body');
		mH = $('#newGuy').height();
	});
	
};

jQuery.fn.equalize = function(){
	
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
	
};

jQuery.fn.truncate = function(options){
	
	var defaults = {
		charNum: 60
	};
	
	var options = $.extend(defaults, options);
		
	return this.each(function() {
		var q = $(this).text();
		var r = q.substr(0,options.charNum);
		$(this).wrapInner('<span class="full"></span>')
		$(this).prepend('<span class="short">'+r+'</span><span class="ells">&#8230;</span>');
	});
};

jQuery.fn.changeDate = function(){
	
	this.each(function() {
		var oldDate = $(this).html();
		var dateArray = oldDate.split(' - ');
		$(this).html('');
		for(var i=0; i<dateArray.length; i++) {
			var date = dateArray[i].split('-');
			var year = date[0];
			var month = date[1];
			var day = date[2];
			switch (month) {
		        case undefined: month = ""; break
				case '01': month = "January"; break
		        case '02': month = "February"; break
		        case '03': month = "March"; break
		        case '04': month = "April"; break
		        case '05': month = "May"; break
		        case '06': month = "June"; break
		        case '07': month = "July"; break
		        case '08': month = "August"; break
		        case '09': month = "September"; break
		        case '10': month = "October"; break
		        case '11': month = "November"; break
		        case '12': month = "December"; break
	        }
			switch (day) {
		        case undefined: day = ""; break
			}
			
			if(day.charAt(0)=='0'){
				day = day.replace("0", "");
			}
			day = day.split(' ').join('');
			
			if(i==0){
				if(day=='' || month==''){ $(this).html(year); }
				else{ $(this).html(month+' '+day+', '+year); }
			}else{
				if(day=='' || month==''){ $(this).append(' - '+year); }
				else{ $(this).append(' - '+month+' '+day+', '+year); }
			}
		}
	});
	
};
/********************************
Added by raju kumar Intelegencia
date 10-june-2010
*********************************/
jQuery.fn.prints = function(){
	// NOTE: We are trimming the jQuery collection down to the
	// first element in the collection.
	if (this.size() > 1){
		this.eq( 0 ).print();
		return;
	} else if (!this.size()){
		return;
	}

	// ASSERT: At this point, we know that the current jQuery
	// collection (as defined by THIS), contains only one
	// printable element.

	// Create a random name for the print frame.
	var strFrameName = ("printer-" + (new Date()).getTime());

	// Create an iFrame with the new name.
	var jFrame = $( "<iframe name='" + strFrameName + "'>" );

	// Hide the frame (sort of) and attach to the body.
	jFrame
		.css( "width", "1px" )
		.css( "height", "1px" )
		.css( "position", "absolute" )
		.css( "left", "-9999px" )
		.appendTo( $( "body:first" ) )
	;

	// Get a FRAMES reference to the new frame.
	var objFrame = window.frames[ strFrameName ];

	// Get a reference to the DOM in the new frame.
	var objDoc = objFrame.document;

	// Grab all the style tags and copy to the new
	// document so that we capture look and feel of
	// the current document.

	// Create a temp document DIV to hold the style tags.
	// This is the only way I could find to get the style
	// tags into IE.
	var jStyleDiv = $( "<div>" ).append(
		$( "link" ).clone()
		);
                 var id=this.attr('id');
               var cls=this.attr('class');
                // var outerdiv="<div id='content'><div id='"+id+"' class='"+cls+"'>";
	// Write the HTML for the document. In this, we will
	// write out the HTML of the current element.
	objDoc.open();
	objDoc.write( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" );
	objDoc.write( "<html>" );
	objDoc.write( "<body>" );
	objDoc.write( "<head>" );
	objDoc.write( "<title>" );
	objDoc.write( document.title );
	objDoc.write( '</title>' );
	objDoc.write( jStyleDiv.html() );
	objDoc.write( "</head>" );
        objDoc.write( "<div id='notPes'><div class='epidermis'><div id='content' class='profile-view clearfix'><div id='trunk'><div id='"+id+"' class='"+cls+"'>" );
	objDoc.write( this.html() );
        objDoc.write( "</div></div></div></div></div>" );
	objDoc.write( "</body>" );
	objDoc.write( "</html>" );
	objDoc.close();

	// Print the document.
	objFrame.focus();
	objFrame.print();

	// Have the frame remove itself in about a minute so that
	// we don't build up too many of these frames.
	setTimeout(
		function(){
			jFrame.remove();
		},
		(60 * 1000)
		);
}



/************************************
Created By                Raju Kumar
Purpose                   To validate email
Company                   Intelegencia
************************************/
function isEmail(str)
			{
			   var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
			
			return regex.test(str);
}


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

