////////////////////////////////////////
// Over Label
////////////////////////////////////////
jQuery.fn.overlabel = function() {
    this.each(function(index) {
        var label = $(this); var field;
        var id = this.htmlFor || label.attr('for');
        if (id && (field = document.getElementById(id))) {
            var control = $(field);
            label.addClass("overlabel-apply");
            if (field.value !== '') {
                label.css("display", "none");
            }
            control.focus(function () {label.css("display", "none");}).blur(function () {
                if (this.value === '') {
                    label.css("display", "block");
                }
            });
            label.click(function() {
                var label = $(this); var field;
                var id = this.htmlFor || label.attr('for');
                if (id && (field = document.getElementById(id))) {
                    field.focus();
                }
            });
        }
    });
};

/*
	from: tweet.seaofclouds.com
*/
$.fn.extend({
  linkUrl: function() {
    var returning = [];
    var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
    this.each(function() {
      returning.push(this.replace(regexp,"<a href=\"$1\" target=\"_blank\">$1</a>"))
    });
    return $(returning);
  },
  linkUser: function() {
    var returning = [];
    var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
    this.each(function() {
      returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>"))
    });
    return $(returning);
  },
  linkHash: function() {
    var returning = [];
    var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
    this.each(function() {
      returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from=roc4life" target=\"_blank\">#$1</a>'))
    });
    return $(returning);
  }
});

function normalizeDate(time) {

	var values = time.split(" ");
	time = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		 delta = delta + (relative_to.getTimezoneOffset() * 60);

	var out = '';
	if (delta < 60)
	{
		out = 'a minute ago';
	} else if(delta < 120)
	{
		out = 'couple of minutes ago';
	} else if(delta < (45*60))
	{
		out = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (90*60))
	{
		out = 'an hour ago';
	} else if(delta < (24*60*60))
	{
		out = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60))
	{
		out = '1 day ago';
	} else
	{
		out = (parseInt(delta / 86400)).toString() + ' days ago';
	}

		return out;
	}

function json(e){var d = document.createElement('script');d.src=e+'&'+new Date().getTime();document.getElementsByTagName('head')[0].appendChild(d);}

function openwin(url,width,height) {
	window.open(url,'hintmag','toolbar=0,status=0,width=' + width + ',height=' + height);
}

// 
// 
// and back to the real meat of everything

$(document).ready(function(){
	
	// newsletter footer
	$('#nl2_form').submit(function() {
		// update user interface
		$('#response_nl2').html('Adding email address...');
		
		// Prepare query string and send AJAX request
		$.ajax({
			url: '/includes/php/store-address.php',
			data: 'ajax=true&email=' + escape($('#nl2_Email').val())+'&newsletter_option1=' + escape($('#nl2_newsletter_kind').val()),
			success: function(msg) {
				$('#response_nl2').html(msg);
			}
		});	
		return false;
	});
	
	// newsletter sidebar
	$('#nl1_form').submit(function() {
		// update user interface
		$('#response_nl1').html('Adding email address...');
		
		// Prepare query string and send AJAX request
		$.ajax({
			url: '/includes/php/store-address.php',
			data: 'ajax=true&email=' + escape($('#nl1_Email').val())+'&newsletter_option1=' + escape($('input[name=nl1_newsletter_kind]:checked').val()),
			success: function(msg) {
				$('#response_nl1').html(msg);
			}
		});	
		return false;
	});
	
	// newsletter header
	$('#nl_form').submit(function() {
		// update user interface
		$('#response_nl').html('Adding email address...');
		
		// Prepare query string and send AJAX request
		$.ajax({
			url: '/includes/php/store-address.php',
			data: 'ajax=true&email=' + escape($('#nl_Email').val())+'&newsletter_option1=' + escape($('#nl_newsletter_kind').val()),
			success: function(msg) {
				$('#response_nl').html(msg);
			}
		});	
		return false;
	});
	
	
	// shareThis
	$('li.social:not(.share-these) a').each(function() {
		$(this).attr('href', $(this).parents('.article').find('h3 a').attr('href'));
	});

	$('li.social.share-these a').each(function() {
		$(this).attr('href', $(this).attr('href').replace( '{url}', 'http://www.hintmag.com' + $(this).parents('.article').find('h3 a').attr('href') ) );
	});
	
	$('#shareThis a').each(function() {
		$(this).attr('href', $(this).attr('href').replace('{url}', window.location));
	});
	
	$('.articalBrief').each(function() {
		var article_url = 'http://www2.hintmag.com/' + $(this).find('h3:first a').attr('href');
		
		$(this).find('.articleInfo.share a').each(function() {
			$(this).attr('href', $(this).attr('href').replace('{url}', article_url));
		});
	
		$(this).find('.controller.share a').click(function() {
			if( $(this).hasClass('close') ) {
				$(this).parents('.articalBrief').find('.articleInfo.share').hide();
				$(this).html('Share').removeClass('close');
			} else {
				$(this).parents('.articalBrief').find('.articleInfo.share').show();
				$(this).html('close').addClass('close');
			}
			
			return false;
		});
		
		$('.articleInfo.share').hide();
	});

	// this is from older code.
	$('a[rel*="external"]').click(function(){
		openwin(this.href, $(this).attr('openwidth'), $(this).attr('openheight'));
		return false;
	});


	$('#superNav form label, #secondaryNewsLetter form label, #tertiaryNewsLetter form label, #newsletterSignup form label, #comments form label').overlabel();
	
  $('.articleInfo .like a').live('click', function(){
     var $this = $(this);
     if($this.hasClass('disabled')) {
       return false;
     } else {
       $this.addClass('disabled');
       // Will Make Request here!
     }
     return false;
  });

	// Share This
	// Please not that i had to do a hard css 
	// "display:none" in the legacy style sheet because i.e. SUCKS!!!!!

	// I feel you!
	$('#shareThis').hide().removeClass('hide');
	
	$('.shareThis').click(function(){
		if ($(this).hasClass('active')){
			$(this).removeClass('active').text('share this page');
			$('#shareThis').slideUp();
		} else {
			$('#shareThis').slideDown();
			$(this).addClass('active').text('close');	
		}
	});
	
  $('#searchForm label').overlabel();
	// Top Newsletter Signup
	// ugh, I think the overlabel() is getting in the way.
	// on .slideUp().slideDown()
	$('#newsletterSignup').slideUp(0);
	
	$('.top_newsletter').click(function(){
		if ($(this).hasClass('active')){
			$(this).removeClass('active').text('Newsletter');
			
			$('#newsletterSignup').addClass('busy').slideUp('normal', function() {
				$(this).removeClass('busy');
			});
		} else {
			$('#newsletterSignup').addClass('busy').slideDown('normal', function() {
				$(this).removeClass('busy');
			});
			
			$(this).addClass('active').text('close');	
		}
	});
	
	// New Departments
	$('#newDepartments li').hover(function(){
		$(this).addClass('hover');
	}, function(){
		$(this).removeClass('hover');
	});
	if(jQuery.fn.cycle){
		
		var newSlides = $('#newSlides .slide img').length;
		var features = $('#features ul li').length;
		var yourPhotos = $('#hintPhotos .carousel ul').length;
		var html = ' ';

		html += '<ul class="slideNav">';
		html += '<li class="prevSlide"><a>Previous</a></li>';
		html += '<li class="nextSlide"><a>Next</a></li>';
		html += '</ul>';
		
		// New
		
		if (newSlides > 1) {
			$('#newSlides .slide').after(html).cycle({
				fx: 'scrollHorz',
				timeout: 0,
				speed: 500,
				prev: '#newSlides  .prevSlide',
				next: '#newSlides  .nextSlide',
				pager:  '#newDepartments ul',
				pagerAnchorBuilder: function(idx, slide) { 
					return '#newDepartments ul li:eq(' + idx + ')'; 
				}, 
				prevNextClick : function(idx, slide) {
					$('#newDepartments ul li:eq(' + slide + ')').siblings('.active').removeClass('active').end().addClass('active');
				}
			});
			
			$('#newDepartments ul li').click(function(){
				if( $(this).hasClass('active') ) {
					window.location.href = $(this).find('h3 a').attr('href');
					$(this).addClass('redirecting');
				}
			});
		}

		
		$('#newDepartments ul li').click(function(){
			if ($(this).hasClass('active')) {
				$(this).removeClass('active');
			} else {
				$(this).siblings('.active').removeClass('active').end()
				.addClass('active');
			}
		});
		$('#newDepartments ul li:first').trigger('click');
		
		
		
		
		// Features
		if (features > 1) {
			$('#features ul').after(html).cycle({
				fx: 'scrollHorz',
				timeout: 0,
				speed: 500,
				prev: '#features  .prevSlide',
				next: '#features  .nextSlide',
				after: function() {
					sIFR.replace(futura, {
						selector: '#page.home #features h4',
						css: '.sIFR-root {color:#999;font-size:12px;min-height:10px;text-align:center;}'
					});
				}
			});
		}
		// Your Photos
		if (yourPhotos > 1) {
			$('#hintPhotos .carousel').after(html).cycle({
				fx: 'scrollHorz',
				timeout: 0,
				speed: 500,
				prev: '#hintPhotos  .prevSlide',
				next: '#hintPhotos  .nextSlide'
			});
		}
	}
	
	// Article Feeds Interior
	$('.article').each(function(){
		
		var id = $(this).attr('id');
		
		var slideHolder = $(this).find('.articlePic');
		var slide = slideHolder.find('.slide');
		var slideX = slide.find('img').width();
		var slideY = slide.find('img').height();
		var slideCount = slide.find('img').length;
		
		var slideNav = ' ';
		slideNav += '<a class="prev">Previous</a>';
		slideNav += '<ul class="slideNav">';
		slideNav += '</ul>';
		slideNav += '<a class="next">next</a>';

		slide.css('width', slideX + 4);
		slideHolder.css('width', slideX + 4);
		
		// Now, If there is more the one <img> in .slide
		// we need to make it a slide show
		if (slideCount > 1) {
			slide.after(slideNav).cycle({
				fx: 'fade',
				timeout: 0,
				speed: 500,
				prev: '#' + id + ' .prev',
				next: '#' + id + ' .next',
				pager : '#' + id + ' .slideNav',
				pagerAnchorBuilder: function(idx, slide) { 
					return '<li><a href="#">'+ (idx+1) +'</a></li>'; 
				},
				before: function( a, img ) {
					var caption = $(img).find('img').attr('alt');
					$(img).parents('.article').find('.articlePic cite').html( ( caption == '' ? '' : caption ) );
				}
			});
			
			
			
		}
		
		
	
	
	
	
		
	
	});
	
	
	
	if(jQuery.fn.fancybox){
/*
		$('.interior .slide a').fancybox({
			overlayOpacity : .85,
			padding : 0
		});
*/
		
		$('a[rel="fancybox"]').fancybox({
			overlayOpacity : .85,
			padding : 0
		});
	}
	
	
	$('#comments form').validate();
	
	
  //  Most
  $('.groupNav li a').each(function(){
    var $this = $(this);
    var target = $this.attr('href').split('#').slice(1); 
    $this.click(function(){
      if($this.hasClass('current')) {
        return false;
      } else {
        $this.addClass('current').parents('.groupNav').find('a.current').not(this).removeClass('current');
        $('.postGroup#'+ target +'').show();
        $('.postGroup:not(#'+ target +')').hide();
        return false;
      }
    });
  });
  
  
  //Heart
  $('.commentCount').click(function(){
    var $this = $(this);
    if($this.hasClass('disabled')){
      return false;      
    }
    else{
      var id = $this.attr('id');      
      $.ajax({
        type: "POST",
        url: "/php/heart.php",
        data: "post_id="+id,
        success: function(data) {
            var c = parseInt( $this.html().replace('LOVE', '').replace('S','') );
            c++;
            $this.html( c + ' LOVE' + ( c == 1 ? '' : 'S' ) );
            $this.addClass('disabled');
        }
      });
    }
    
    return false;
  });

});

function View(category){
  $(".article").each(function(){
    if ($(this).hasClass(category)){
      $(this).show(0);
    }
    else{
      $(this).hide(0);
    }
  });
}
