$(document).ready(function() {
	$('div.title').click(function() {
		$(this).next().toggle('fast', adjust);
	});
	$('div.title').hover(
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);

	$('div.body_menu:first,div.body:first').show();
	
	$(window).resize(adjust);
	$('#message_area').resize(adjust);
	adjust();
});

function adjust() {
	$('#root').height($(window).height() - $('#head_title').height());
	$('#contents').height($('#root').height() - $('#message_area').height());
}

// general error handler
$.ajaxSetup({
	error: function(xhr, status, e) {
		$('#messages').show('fast');
		addMessage('Server Error (status : ' + status + ').');
		addMessage(xhr.responseText, true);
		processing = false;
	}
});


function addMessage(messages, notPre) {
	if (!(messages instanceof Array)) {
		messages = [messages];
	}
	var open = notPre ? '<div>' : '<div class="error"><pre>';
	var close =  notPre ? '</div>' : '</pre></div>';

	$.each(messages, function(i, v) {
		$('#messages').append(open + v + close);
	});
	$('#messages').show('fast', adjust);
}


/**
 * Common functions 
 */
function sprintf(){
	var format = arguments[0]; // format
	var args   = arguments;
	var i = 0;
	return format.replace(/%s/g, function(){
		i++;
		return args[i];
	});
}


function get(action, data, callback) {
	$.get(base_url + action, data, function(res) {
		if (isValid(res)) {
			callback(res);
		}
	}, 'json');
}
function post(action, data, callback) {
	data['auth_token'] = token;
	$.post(base_url + action, data, function(res) {
		if (isValid(res)) {
			callback(res);
		}
	}, 'json');
}

//check json error object
function isValid(json) {
	processing = false;
	if (!json || (json.errors && json.errors.length)) {
		if (!json) {
			addMessage('unexpected error.');
		} else {
			addMessage(json.errors);
		}
		return false;
	} else {
		return true;
	}
}

// server call flag
var processing = false;
function process(event) {
	processing = true;
	var tar = $(event.target);
	tar.attr('disabled', 'disabled');

	$('#d').remove();
	$('body').append('<div id="d">processing...</div>');
	$('#d').css('top', tar.offset().top + 10).css('left', tar.offset().left + 10);
	$('#d').css('background-color', '#ffc').css('border-color', '#ff5').text('processing...');

	$("#d").show('fast');
	function runIt() {
		if (processing) {
			$("#d").animate({opacity: 0.5}, null);
			$("#d").animate({opacity: 1}, null, null, runIt);
		} else {
			tar.attr('disabled', '');
			$('#d').css('background-color', '#ccf').css('border-color', '#55f').text('done.');
			$('#d').fadeOut(2000);
		}
	}
	runIt();
}


function validateForm(form, rulesList) {
	var valid = true;
	jQuery.each(rulesList, function(i, v) {
		valid &= validate(form + ' [name=' + i + ']', v);
	});
	return valid;
}

function validate(target, rules) {
	var valid = true;
	jQuery.each(rules, function(i, f) {
		valid &= f($(target));
	});
	if (valid) {
		$(target).removeClass('invalid');
	} else {
		$(target).addClass('invalid');
	}
	return valid;
}
function required(target) {
	return !!target.val();
}
function isNumeric(target) {
	return !isNaN(target.val());
}
function isDate(target) {
	var d = new Date(target.val().replace(/\./g, ':'));
	return !target.val() || (d != 'NaN' && d != 'Invalid Date');
}
function maxLength(len) {
	return function(target) {
		return (typeof(target.val()) == 'string') && target.val().length <= len;
	}
}
function minLength(len) {
	return function(target) {
		return !target.val() || (typeof(target.val()) == 'string' && target.val().length >= len); 
	}
}

//base64
function encode64(input) {
    var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ";
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
 
    do {
       chr1 = input.charCodeAt(i++);
       chr2 = input.charCodeAt(i++);
       chr3 = input.charCodeAt(i++);
 
       enc1 = chr1 >> 2;
       enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
       enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
       enc4 = chr3 & 63;
 
       if (isNaN(chr2)) {
          enc3 = enc4 = 64;
       } else if (isNaN(chr3)) {
          enc4 = 64;
       }
 
       output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
          keyStr.charAt(enc3) + keyStr.charAt(enc4);
    } while (i < input.length);
   
    return output;
}
