/**
 * @package WordPress
 * @subpackage SmashingMagazine_Theme
 * @maintainer Smashing Media <admin@smashing-media.com>
 */

var ajaxurl = globals.wp_home+'/wp-admin/admin-ajax.php';

var contactForm =
{
    submit: function(event)
    {
        $('.contactform form.smashform input[type="submit"]').attr('disabled', 'disabled');
        $('.contactform form.smashform .container span.error').html('');

        var data = $('.contactform form.smashform').serialize();

        if(data.length>0)
        {
            data = data+"&action=validateSmashContactFormHandler";
        } else {
            data = "action=validateSmashContactFormHandler";
        }

        $.post(globals.wp_home+'/wp-admin/admin-ajax.php', data, function(response)
        {
            if($.fn.jquery == '1.2.6')
            {
                response = JSON.parse(response);
            }

            $.each(response.fields, function(index, value)
            {
                $('.contactform form.smashform .container.'+index+' span.error').html('<p>'+value+'</p>');
            });
            $('.contactform form.smashform input[type="submit"]').removeAttr("disabled");

            if(response.fields && response.fields.length == 0)
            {
                window.location = '/contact-form-thank-you/';
            } else {
                //$('body').stop().scrollTo( $("span.error p:nth-child(1)"), 100 );
            }
        });

        return false;	
    },

    restrict: function(event)
    {
        var l = $('.contactform #msg').val().length;
        var max = 420;

        $('.contactform #formlimitcounter').html(max-l<1?"0":max-l);

        if( l >= max-max*0.1)
        {
            $(".contactform #formlimitcountermsg").stop().fadeTo(150, 0.25, function()
            {
                $(".contactform #formlimitcountermsg").fadeTo(150, 1);
            });
        }

        if( l >= max)
        {
            $('.contactform #msg').val(jQuery('.contactform #msg').val().substr(0,max));
        }
    }
}

$(function() {

	$("select#subsection-select").change(function () { location.href = $(this).val(); });

   	$.keyNav();
	$.whenPressed('j',function(){
		$('#keyboard-navigation a.prev').navigateTo();
	});
	$.whenPressed('k',function(){
		$('#keyboard-navigation a.next').navigateTo();
	});
	$.whenPressed('h',function(){
		$().navigateTo('#top');
   	});
	/*
	$.whenPressed('l',function(){
		$().navigateTo('#comments');
   	});
	*/
	$.whenPressed('s',function(){
		$().navigateTo('#top');
		$('.wp-search-form input[name=q]').focus();
   	});

	if($('.contactform').size())
	{
		contactForm.restrict();
	        $('.contactform #msg').keyup(contactForm.restrict);
	        $('.contactform form.smashform').submit(contactForm.submit);
	}
	
	//Fix bottom-border of anchors with a child img
	$('a img').parents('a').css({border: 'none'});
	
	//Removed all fixed width and height values from images
	$('img').removeAttr('width').removeAttr('height');

	$("select#networkselection").change(function () { location.href = $(this).val(); });
	$("form#search select").change(function() { $(this).prevAll(".select-content").text($(this).val()); });
	
	if($(".sub-tabs").size())
	{
	   var subTabber = jQuery( '.subtab-pages > div' );
	   $( '.sub-tabs li > a' ).click(function()
	   {
	       subTabber.hide();
	       subTabber.filter(this.hash).show();
	       $( '.sub-tabs li > a' ).removeClass( 'active' );
	       $(this).addClass( 'active' );
	       return false;
	   }).filter( ':first' ).click();
	}

	$('#tweetlist li a.tweet-status' ).timeago();
	SyntaxHighlighter.config.clipboardSwf = 'http://media.smashingmagazine.com/themes/smashingv4/js/sh/clipboard.swf';
	SyntaxHighlighter.all();
	
	initSubjectHighlighting();
	selectMenu();
	footnotes();
});

function footnotes()
{

	var links = $('.post p:not(.longtags) a[href]:not([href^=#],[href^=mailto],[rel=nofollow]), .post ul a[href]:not([href^=#],[href^=mailto],[rel=nofollow])');
	var notelist = $('<ul class="print_only_notelist"></ul>').insertAfter($('.post'));
	var i = 0;
	
	$('<li>', { html: '<h4>Footnotes:</h4>' }).appendTo(notelist);
	$.each(links, function(i){
		var parent_class = $(this).parent().attr('class');
		if(parent_class.indexOf('author') == -1 && parent_class.indexOf('tags') === -1 && parent_class.indexOf('edit') === -1 && parent_class.indexOf('social-icons') === -1)
		{
			var link_url = $(this).attr('href');
			var link_text = $(this).text();
			if(link_url !== '' && (/^https?:\/\//.test(link_url)))
			{
				if(link_url.search(/\.(jpg|jpeg|gif|png|ico|css|js|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|mp3)/) === -1)
				{
					i = i+1;
					$('<sup>',{text:' '+i+''}).addClass('print_only').insertAfter($(this));				
					if(link_text.length > 0)
					{
						var ftext = link_text+' - '+link_url;
					}else{
						var ftext = link_url;
					}
					$('<li>', { html: '<sup>'+i+'</sup> '+ftext }).appendTo(notelist);
				}
			}
		}
	});
}

function selectMenu()
{
	var selectMenu = $("#search select");
	$('<input id="'+selectMenu.attr('id')+'-hidden" type="hidden" name="'+selectMenu.attr('name')+'" value="" />').insertAfter(selectMenu);
	selectMenu.hide();
	
	var newSelectMenu = '<div class="selectmenu"><div class="selectmenu-selected"><a rel="placeholder">Everything</a></div><ul class="selectmenu-menu"><li><a rel="placeholder">Everything</a></li>';

	selectMenu.find('option:gt(0)').each(function(){
		newSelectMenu += '<li><a rel="'+$(this).val()+'">'+$(this).text()+'</a></li>';
	});
	
	newSelectMenu += '</ul></div>';
	
	$(newSelectMenu).insertAfter(selectMenu);

	var newSelectMenu = $('div.selectmenu');
	
	$('div.selectmenu-selected a', newSelectMenu).live('click', function(){
		
		$('ul.selectmenu-menu', newSelectMenu).toggle();
		
		return false;
	});
	
	$('body').live('click', function(){
		$('ul.selectmenu-menu', newSelectMenu).hide();
	});
		
	$('ul.selectmenu-menu a', newSelectMenu).live('click', function(){
		
		var optionValue = $(this).attr('rel');
		var optionText = $(this).text();
		
		$('ul.selectmenu-menu', newSelectMenu).hide();
		
		$('div.selectmenu-selected a', newSelectMenu).text(optionText);
		$('#'+selectMenu.attr('id')+'-hidden').val(optionValue);
		
		var activeMessageType = $('ul.message-type.active');
			
		if(activeMessageType.length) {
		    activeMessageType.slideUp(300, function(){
		    	$('#'+optionValue).addClass('active').slideDown(300);
		    }).removeClass('active');
		} else {
		    $('#'+optionValue).addClass('active').slideDown(300);
		}		
		
		return false;
	});	
}

function initSubjectHighlighting()
{
	// if contact found in url, get query-param
	if(/\/contact?.+\//i.test(location.pathname)) {
		var getparam = (unescape(location.search).length>0)?unescape(location.search.split('?')[1]):'';
		// Check whether get-param was appended@url and highlight/select the subject 
		if(getparam !== '' && getparam !== 0) {
			// Is not numeric, match by subject
			if(isNaN(getparam)) {
				var inputEl = $('input[value='+getparam+']');
				// If inputfield exist with get-param, select input and highlight label text
				if(inputEl.length>0) {
					inputEl.parent('label').html('<input type="radio" value="'+getparam+'" name="subject" class="radio" checked="checked"><span class="highlighted">'+getparam+'</span>');
				}
			// Is numeric, match by index-id
			}else{
				// Type-Conversion: string to integer
				var idx = parseFloat(getparam);
				// if index-number in range, select input and highlight label text
				if(idx >= 1 || idx < $('.subject label').length) {
					var label = $('.subject label').slice(idx,idx+1);
					var text = label.text();	
					label.html('<input type="radio" value="'+text+'" name="subject" class="radio" checked="checked"><span class="highlighted">'+text+'</span>');
				}
			}
			// Change-event to remove marker from highlighted textfield
			$('.subject label input').change(function(e) {
				e.preventDefault();
				$('.subject label span.highlighted').removeClass('highlighted');
			});
		}
	}
}
