
var addthis_pub="crasman";  // account for addthis.com service
var messages = {};  // i18n messages

function refresh_checkbox(label, init) {
	var input = $('#' + $(label).attr('for'));
	$(label)[input.attr('checked', ! (init ^ input.attr('checked'))).attr('checked') ?
		'addClass' : 'removeClass'](label.className.split(' ')[0] + '-checked');
}


function session_id() {
	return $.cookie('cm_public_session');
}


$(document).ready(function() {

	if ($.browser.msie && $.browser.version < 7) {

		$('#header LI.language').hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
		
		$('LI:first-child').addClass('first-child');
		$('DIV:first-child').addClass('first-child');
	}

	$('#footer .search LABEL').each(function() { refresh_checkbox(this, true) })
		.click(function(e) { refresh_checkbox(this); e.preventDefault() });

	$('FORM DIV.submit, FORM A.submit').click(function(e) {
		e.preventDefault();
		$(this).parents('FORM:first').submit();
	});

	$('FORM').submit(function() {
		$('.autoclear-default', this).val('');
	});

	$('FORM DIV.reset, FORM A.reset').click(function(e) {
		e.preventDefault();
		$(this).parents('FORM:first').find('INPUT[type=text], TEXTAREA').each(function() {
			if (! $(this).hasClass('autoclear-default')) {
				$(this).val('');
			}
		});
	});
	
	$('FORM.section-poll').submit(function() {
		var form = this;
		var checked = $('INPUT[type=radio]:checked', this);
		if (checked.length > 0)
			var index = checked.val();
		else return false;
		var result = $(document.createElement('div'))
			.addClass('results')
			.load($(this).attr('action'), {
				q0: $('INPUT[name=poll]', this).val(),
				q1: index,
				q2: session_id(),
				ngf_okparams: $('INPUT[name=ngf_okparams]', this).val()
			}, function() {
				$('FIELDSET', form).hide();
				$(result).appendTo(form);
			});
		return false;
	});
	
	if ($('#comment-article').length > 0) {
		var msecs = new Date().getTime();
		var input = $('#comment-article .are-you-human INPUT').val('');
		window.setTimeout(function() {
			input.val((new Date().getTime() - msecs));
		}, 5000);
	}

	$('#comment-article').submit(function(e) {

		var field_name = $('[name=q0]', this);
		var field_email = $('[name=q1]', this);

		if ($('.are-you-human INPUT', this).val() < 3000) {
			alert('Please wait 5 seconds and try again.');
			$('.autoclear', this).blur();
			return false;
		}
		if (field_name.val() == '') {
			alert(messages['name_is_required_field']);
			$('.autoclear', this).blur();
			field_name.focus();
			return false;
		}
		if (field_email.val().indexOf('@') == -1) {
			alert(messages['email_is_required_field']);
			$('.autoclear', this).blur();
			field_email.focus();
			return false;
		}
		if ($('.input-comment', this).val() == '') {
			alert(messages['empty_comment_not_allowed']);
			$('.input-comment', this).focus();
			$('.autoclear', this).blur();
			return false;
		}
	});
	
	$('.write-comment').click(function() {
		$('#comment-article').show();
		window.location.href = '#comment-article';
		$('TEXTAREA:first', '#comment-article').focus();
	});
	
	$('#article-toolbar .print').click(function(e) {
		e.preventDefault();
		var print_sheets = $('HEAD LINK[rel=stylesheet][media=print]').attr('media', 'all');
		$('BODY').click(function() {
			print_sheets.attr('media', 'print');		
		});
		window.print();
		if ($.browser.msie)
			alert('Click OK to switch back to normal view.');
	});
	
	$('#header .search .dig-query').james('/search/autocomplete', { onSelect: function(data, json) {
		if (json.url && json.url.indexOf('http://') == 0) {
			window.location.href = json.url;
		} else {
			return data;
		}
	}, onKeystroke: function(data) {
		return data;
	} });
	
	$('.scrollable-gallery').each(function() {

		var gallery = new ScrollableGallery(this);
		
		// Open a gallery item popup if its id is given as an anchor
		var anchor_idx = window.location.href.indexOf('#');
		if (anchor_idx != -1) {
			var gallery_item = window.location.href.substr(anchor_idx + 1);
			$('#' + gallery_item + ' A').click();
		}
	});
	
	$('.toolbar .mail').click(function(e) {
		e.preventDefault();
		$('#popup-share-link INPUT[name=url]').val(window.location.href);
		$('#popup-share-link').toggle();
	});
	
	$('.popup .toolbar .close').click(function() {
		$(this).parents('.popup:first').hide();
	});
	
	$('#popup-share-link INPUT[name=url]').each(function() {
		$(this).val(window.location.href);
	});

	$('#popup-share-link FORM').submit(function() {
		$('INPUT.email', this).each(function() {
			$(this)[$(this).val().indexOf('@') == -1 ? 'addClass' : 'removeClass']('invalid');
		});
		var invalid = $('.invalid:first', this);
		if (invalid.length > 0) {
			window.alert(messages['invalid_email']);
			invalid.focus();
			return false;
		}
		var f = $(this);
		f.append('<input type="hidden" name="mail_sendnow" value="1" />');
		var loading = f.find('.loading').fadeIn();
		post_form(this, function(data, textStatus) {
			window.setTimeout(function() {
				f.hide();
				var msg = f.parent().find('.msg').html(data).show();
				window.setTimeout(function() {
					$('#popup-share-link').fadeOut('slow', function() {
						f.show();
						loading.hide();
						msg.hide();
					});
				}, 1500);
			}, 1000);
		});
		return false;
	});

	$('FORM .autoclear').focus(function () {
		if ($(this).hasClass('autoclear-default')) {
			$(this).removeClass('autoclear-default');
			$(this).addClass('autoclear-edited');
			$(this).val('');
		}
	}).blur(function () {
		if ($(this).val() == '') {
			$(this).addClass('autoclear-default');
			$(this).removeClass('autoclear-edited');
			$(this).val($(this).attr('default_value'));
		}
	}).each(function() {
		$(this).attr('default_value', $(this).val());	
	});
	

	/* Hide overflown TOC list-items and show "show more" link (= hack by customer request) */
	$('#content .section-toc-expandable').each(function() {
		var toc = this;
		$('LI', toc).each(function() {
			if ($(this).position().top + $(this).height() > $(toc).height()) {
				$(this).addClass('overflown');
			}
		});
		$('LI.overflown', toc).hide();
		if ($('LI.overflown', toc).length > 0) {
			var more = $('.show-rest', toc).show();
			if (more.position().top + more.height() > $(toc).height()) {
				$('LI.overflown:first', toc).prev().hide();
			}
			more.click(function(e) {
				e.preventDefault();
				more.hide();
				$('LI', toc).show();
				$(toc).animate({ 'height': $('UL', toc).height() + $('H3', toc).height() + 20 }, {
					complete: function() {
					}
				});
			});
		}
	});
				
});

function post_form(form, callback) {
	var f = $(form);
	var params = {};
	$(':input', f).each(function() {
		params[$(this).attr('name')] = $(this).val();
	});
	$.post(f.attr('action'), params, callback);
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        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();
        }
        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 {
        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]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



/**
 * jQuery autocomplete plugin
 * Copyright (c) <2008> <Sebastien RANNOU> - The MIT License
 * http://plugins.jquery.com/project/james
 */

jQuery.fn.james=function(url_to_call,options){var that=jQuery(this),results_set=[],current_hovered_rank=0,keyEvents=[{keycode:38,action:function(){keyEventKeyUp();}},{keycode:40,action:function(){keyEventKeyDown();}},{keycode:13,action:function(){keyEventEnter();}},{keycode:27,action:function(){keyEventEsc();}}],ul_element=false,o=jQuery.extend({onKeystroke:function(data){return data;},onSelect:function(dom_value,json_obj){that.attr("value",results_set[current_hovered_rank].text);},keydelay:300,minlength:3,method:"get",varname:"input_content",params:""},options||{});(function initDOM(){var ul_id=false;var ul_node=document.createElement("ul");var genUniqueId=function(){var result="ul_james_"+Math.round(Math.random()*424242);if(jQuery("#"+result).length>0)
{result=genUniqueId();}
return result;};ul_id=genUniqueId();jQuery(ul_node).attr("id",ul_id).addClass("ul_james");that.after(ul_node);ul_element=jQuery("#"+ul_id);ul_element.hide();})();var initCSS=function initCSS(){var input_offset=that.offset();ul_element.css({top:input_offset.top+that.outerHeight(),width:that.outerWidth(),left:input_offset.left,position:"absolute"});}
that.keydown(function(event){if(event.keyCode===13)
{return false;}});var keyevent_current_timer=false;that.keyup(function(event){var is_specific_action=false;for(var i=0;keyEvents[i];i++)
{if(event.keyCode===keyEvents[i].keycode)
{is_specific_action=true;keyEvents[i].action();break;}}
if(is_specific_action===false)
{if(keyevent_current_timer!==false)
{window.clearTimeout(keyevent_current_timer);keyevent_current_timer=false;}
keyevent_current_timer=window.setTimeout(function(){ajaxUpdate();},o.keydelay);}});var ajaxUpdate=function(){var value_to_send=that.attr("value");if(value_to_send.length>0&&(o.minlength===false||value_to_send.length>=o.minlength))
{$.ajax({type:o.method,data:o.varname+"="+value_to_send+"&"+o.params,url:url_to_call,dataType:"json",success:function(data){var arr=o.onKeystroke(data);results_set=[];current_hovered=0;for(var i in arr)
{if(arr[i]!==null)
{if(typeof(arr[i].json)==="undefined")
{results_set.push({text:arr[i],json:{}});}
else
{results_set.push({text:arr[i].text,json:arr[i].json});}}}
updateDom();}});}
else
{cleanResults();}}
var updateDom=function(){jQuery(ul_element).empty();var is_empty=true;initCSS();for(var i in results_set)
{if(results_set[i]!==null)
{var li_elem=document.createElement("li");jQuery(li_elem).addClass("li_james");if(i==(current_hovered_rank%results_set.length))
{jQuery(li_elem).addClass("li_james_hovered");}
jQuery(li_elem).append(results_set[i].text);jQuery(ul_element).append(li_elem);bind_elem_mouse_hover(li_elem,i);is_empty=false;}}
if(is_empty)
{jQuery(ul_element).hide();}
else
{jQuery(ul_element).show();}}
var bind_elem_mouse_hover=function(elem,i){jQuery(elem).hover(function(){jQuery(ul_element).find(".li_james_hovered").removeClass("li_james_hovered");jQuery(elem).addClass("li_james_hovered");current_hovered_rank=i;},function(){jQuery(elem).removeClass("li_james_hovered");current_hovered_rank=0;});jQuery(elem).click(function(){keyEventEnter();});}
var cleanResults=function(){jQuery(ul_element).empty();jQuery(ul_element).hide();results_set=[];current_hovered_rank=0;}
var keyEventKeyUp=function(){if(current_hovered_rank>0)
{current_hovered_rank--;}
else if(results_set.length)
{current_hovered_rank=results_set.length-1;}
updateDom();}
var keyEventKeyDown=function(){if(current_hovered_rank<(results_set.length-1))
{current_hovered_rank++;}
else
{current_hovered_rank=0;}
updateDom();}
var keyEventEnter=function(){if(results_set.length>0)
{that.attr("value",o.onSelect(results_set[current_hovered_rank].text,results_set[current_hovered_rank].json));}
cleanResults();}
var keyEventEsc=function(){that.attr("value","");cleanResults();}};
