// ---------------------------------------------------------------------------------
//	embedded AJAX forms
// ---------------------------------------------------------------------------------
var ajaxFormCallback = null;
// ---------------------------------------------------------------------------------
function ajaxFormLoad(url, callback)
{
	ajaxFormCallback = callback;

	$.fn.colorbox({ html: '<div id="ajaxForm"><div id="loadingBox"><img src="/helpers/form/images/ajax-loader.gif" /><div></div>', title: 'Edit Window', opacity: 0.50, close: 'Close', transition: 'none', scrolling: false, speed: 200 });
	
	$.ajax({ url: url, data: { html: 'true' }, dataType: 'html', success: function(data) {
		$.fn.colorbox({ html: '<div id="ajaxForm"><div id="ajaxBox">' + data + '</div></div>', scrolling: false, transition: 'elastic', speed: 200 });
		$('.upload').each(upload);
	}});
	return false;
}
// ---------------------------------------------------------------------------------
function ajaxFormSubmit(obj)
{
	var hash = $('#ajaxForm form').formHash();
	var url = $('#ajaxForm form').attr('action');
	
	hash.ajax = 'true';

	$.fn.colorbox.close();

	$.ajax({ url: url, data: hash, dataType: 'json', success: ajaxFormCallback });
	return false;
}
// ---------------------------------------------------------------------------------
function ajaxCopy()
{
	var r = confirm("Are you sure you want to copy this entry?");
	if (r == true)
	{
		var url = '/' + controller + '/copy/' + id;
		$.ajax({ url: url, data: { ajax: 'true' }, dataType: 'html', success: function(data) {
			$.fn.colorbox.close();
			ajaxFormCallback(data);
		}});
	}
	return true;
}
// ---------------------------------------------------------------------------------
function ajaxAbandon()
{
	$.fn.colorbox.close();
}
// ---------------------------------------------------------------------------------
function ajaxDelete(obj, controller, id)
{
	var r = confirm("Are you sure you want to delete this user?");
	if (r == true)
	{
		var url = '/' + controller + '/delete/' + id;
		$.ajax({ url: url, data: { ajax: 'true' }, dataType: 'html', success: function(data) {
			$.fn.colorbox.close();
			ajaxFormCallback(data);
		}});
	}
	return true;
}
// ---------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------
function select_trigger(from, to, url)
{
	$('#' + from).change(function() {
		$('#' + to).html('<option>Loading Selections...</option>');
		$.getJSON(url + '/' + $('#' + from).val(), { }, function(data) {
			var soptions = '';
			for (var x in data) {
				soptions += '<option value="' + x + '">' + data[x] + '</option>';
			}
			$('#' + to).html(soptions);
		});
	});
}
// ---------------------------------------------------------------------------------
function form_multi_date(name, day_required, month_required, name2)
{
	if (name2 != '')
		document.getElementById(name2).value = 0;
	if (document.getElementById(name+'_1').selectedIndex == 0) return;
	if (document.getElementById(name+'_2').selectedIndex == 0)
	{
		if (month_required)
			return;
		else
			document.getElementById(name2).value++;
	}
	if (document.getElementById(name+'_3').selectedIndex == 0)
	{
		if (day_required)
			return;
		else
			document.getElementById(name2).value++;
	}

	var y = document.getElementById(name+'_1').value;
	var m = document.getElementById(name+'_2').value;
	if (m < 1) m = "12";
	var d = document.getElementById(name+'_3').value;
	if (d < 1) d = "31";

	document.getElementById(name).value = y + '-' + m + '-' + d;
}
// ---------------------------------------------------------------------------------
function form_multi_phone(name)
{
	var a1 = document.getElementById(name+'_1').value;
	var a2 = document.getElementById(name+'_2').value;
	var a3 = document.getElementById(name+'_3').value;
	var a4 = document.getElementById(name+'_4').value;

	document.getElementById(name).value = a1 + "-" + a2 + "-" + a3 + " " + a4;
}
// ---------------------------------------------------------------------------------
function form_multi_time(name)
{
	var h = parseInt(document.getElementById(name+'_1').value);
	var m = document.getElementById(name+'_2').value;

	if(h<10) h = "0" + h;

	var output = h + ':' + m + ':' + '00';
	document.getElementById(name).value = output;
}
// ---------------------------------------------------------------------------------
function form_multi_datetime(name)
{
	var y = document.getElementById(name+'_1').value;
	var m = document.getElementById(name+'_2').value;
	var d = document.getElementById(name+'_3').value;
	var h = parseInt(document.getElementById(name+'_4').value);
	var min = document.getElementById(name+'_5').value;

	if(h<10) h = "0" + h;

	var output = y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + '00';
	document.getElementById(name).value = output;
}
// ---------------------------------------------------------------------------------
function image_start(id)
{
	$('#'+id+'_new').css('height', '0px').css('width', '0px');
	$('#'+id+'_prog').show();
}
// ---------------------------------------------------------------------------------
function image_finish(id, image_id, image_url)
{
	$('#'+id+'_prog').hide();
	$('#'+id+'_photo').attr('src', image_url);
	//$('#'+id+'_name').attr('value', image_id);
	$('#'+id+'_name').attr('value', image_url);
	$('#'+id+'_file').show();
}
// ---------------------------------------------------------------------------------
function image_delete(id)
{
	$('#'+id+'_file').hide();
	$('#'+id+'_new').css('height', '23px').css('width', '400px');
	$('#'+id+'_name').attr('value','');
	return false;
}
// ---------------------------------------------------------------------------------
function submit_processing()
{
	for (var i = 0; i < codepress_object.length; i++) 
		codepress_object[i].toggleEditor();
}
// ---------------------------------------------------------------------------------
var field_id = 1;
var cTime = new Date();
var field_tag = cTime.getTime();
var groupNone = false;
// ---------------------------------------------------------------------------------
function labelGroupLine(name)
{
//	proto = $('#' + name + ' tr.proto td:first').html();
	var count = 0;
	$('#' + name + ' .groupLine').each(function(i) {
		count++;
//		if (++count > 3) $('td:first', this).html('');
//		else if (count == 3) $('td:first', this).html(proto);
	});
	return count;
}
// ---------------------------------------------------------------------------------
function triggerShow(obj)
{
	obj.show();
	$(':input', obj).each(function() {
		name = $(this).attr('name');
		parts = name.split('.');
		if (parts[0] == 'hide') {
			$(this).attr('name', parts[1]);
		}
	});
}
// ---------------------------------------------------------------------------------
function triggerHide(obj)
{
	obj.hide();
	$(':input', obj).each(function() {
		name = $(this).attr('name');
		parts = name.split('.');
		if (parts[0] != 'hide') {
			$(this).attr('name', 'hide.' + name);
		}
	});
}
// ---------------------------------------------------------------------------------
function triggerLine()
{
	var name = $(this).attr('name');
	var regex = /\[(\w+)\]$/;
	var parts = regex.exec(name); 
	var group = $(this).parents('.groupLine').eq(0);

	$('option', group).each(function() {
		ovalue = $(this).val();
		oDiv = $('.' + parts[1] + '_' + ovalue, group);
		$(this).attr('selected') ? triggerShow(oDiv): triggerHide(oDiv);
	});
}
// ---------------------------------------------------------------------------------
function addGroupLineCore(name, field, id, values, errors)
{
	if (id == undefined) id =  + field_tag + '_' + field_id++;
	var record_name = name + '[data][' + id + ']';

	line = $('#' + name + ' tr.proto').eq(0).clone().removeClass('proto').addClass('groupLine').appendTo('#' + name);
	$(':input', line).each(function (i) {
		fname = $(this).attr('name');
		ffname = record_name + '[' + fname + ']';
		fvalue = ((values == undefined) || (values[fname] == undefined)) ? '' : values[fname];
		evalue = ((errors == undefined) || (errors[fname] == undefined)) ? false : true;
		$(this).attr('name', ffname)
		if ($(this).attr('type') != 'checkbox') $(this).attr('value', fvalue);
		else if (fvalue != '') $(this).attr('checked', true);
		if (evalue) $(this).css({ backgroundColor: '#fdd', border: '1px solid #900', padding: '2px' });
	});
	$('.trigger', line).each(triggerLine).change(triggerLine);
	$('.upload', line).each(upload);
	if (typeof groupCallback == 'function') groupCallback(line);
	var count = labelGroupLine(name);
}
// ---------------------------------------------------------------------------------
function addGroupLine(ptr, field)
{
	name = $(ptr).parents('table').andSelf().eq(0).attr('id');
	addGroupLineCore(name, field);

	return false;
}
// ---------------------------------------------------------------------------------
function delGroupLine(ptr, field)
{
	name = $(ptr).parents('table').andSelf().eq(0).attr('id');
	$(ptr).parents('.groupLine').eq(0).remove();
	if ((labelGroupLine(name) < 1) && (groupNone == false)) {
	//	alert(groupNone);
		addGroupLineCore(name, field);
	}
	return false;
}
// ---------------------------------------------------------------------------------
function addGroupInit(name, field, values, errors, none)
{
	if ((none != undefined) && (none == true)) groupNone = true;
	if (values != undefined) {
		for (var id in values) {
			if ((errors == undefined) || (errors[id] == undefined))
				addGroupLineCore(name, field, id, values[id]);
			else addGroupLineCore(name, field, id, values[id], errors[id]);
		}
	} else if (groupNone == false) addGroupLineCore(name, field);
}

// ---------------------------------------------------------------------------------
//	upload form element
// ---------------------------------------------------------------------------------

var upload_id = 1;
// ---------------------------------------------------------------------------------
//	<div class="upload">
//		<div class="wait">Waiting to Upload</div>
//		<div class="send">Uploading to Server</div>
//		<div class="view">
//			<img src="blank.gif" class="sample" />
//			<div class="filter">ksl/img30</div>
//			<div class="summary">summary</div>
//			<div class="url">the url</div>
//			<a class="delete" href="#">delete</a>
//		</div>
//		<input class="data" type="hidden" name="upload_data" />
//	</div>
// ---------------------------------------------------------------------------------
function upload()
{
	if ($(this).parents('.proto').length) return;
	var box = $(this);
	// changes from nick 03/16 to work with jquery 1.3.1
	// modified by andrew 02/03/2010 to make this work with on a field more than once
	if ((box.attr('id') == undefined) || (box.attr('id') == ""))
	{ 
		id = 'upload_id_' + upload_id++;
		box.attr('id', id);
	
		var html = "";

		if ($('.delete', box).length) {
			$('.delete', box).replaceWith("<a href=\"#\" class=\"delete\" onclick=\"return upload_delete('" + id + "');\">" + $('.delete', box).html() + "</a>");
		}
		if ($('.wait', box).length < 1) html += "<div class=\"wait\">Waiting to Upload</div>";
		if ($('.send', box).length < 1) html += "<div class=\"send\">Uploading to Server...</div>";
		if ($('.view', box).length < 1) html += "<div class=\"view\"><a class=\"delete\" href=\"#\" onclick=\"return upload_delete('" + id + "');\">delete</a><div class=\"summary\"></div></div>";
		if ($('.find', box).length < 1) html += "<input class=\"find\" type=\"file\" name=\""+id+"\" onchange=\"return upload_start(this, '"+id+"');\"/>";
			else $('.find', box).attr('name', id).change(function(){upload_start(this,id);});
		if ($('.frame', box).length < 1) html += "<iframe name=\"" + id + "_frame\" style=\"display: none;\" src=\"about:blank\"></iframe>";
			else $('.frame', box).attr('name', id + '_frame').attr('src','about:blank').css('display','none');
		box.append(html);
	}
	value = $('.data', box).eq(0).val();
	
	$('.filter', box).hide(); // never show the filter name

	if (value) {
		upload_done(box, value);
		$('.find', box).hide();
		$('.wait', box).hide();
		$('.send', box).hide();
	}
	else {
		$('.find', box).show();
		$('.wait', box).hide();
		$('.send', box).hide();
		$('.view', box).hide();
	}
}
// ---------------------------------------------------------------------------------
function upload_start(obj, id)
{
	var obj = id instanceof jQuery ? id : $('#' + id);

	var form = obj.parents('form');
	if ((action = form.attr('action')) == undefined) action = '';

	form.attr('target', id + '_frame').attr('action', '/upload/send/');
	form.submit();
	form.attr('target', '').attr('action', action);
	$('.find', obj).val('');

	$('.find', obj).eq(0).hide();
	$('.send', obj).show();

	return false;
}
// ---------------------------------------------------------------------------------
function upload_done(id, data)
{
	var obj = id instanceof jQuery ? id : $('#' + id);

	var dx = data.split('|');

	var filter = $('.filter', obj).html();
	var photo = dx[0];
	if(filter){
		photo = photo + '?filter=' + filter;
	}
	$('.send', obj).hide();
	$('.data', obj).val(data);
	$('.find', obj).val('');
	var bytes = parseInt(dx[1] / 1000);
	var range = 'Kb';
	if (bytes > 1000) {
		bytes = parseInt(bytes / 1000);
		range = 'Mb';
	}
	$('.view .summary', obj).html('<a class="link" href="' + dx[0] + '" target="_blank">' + dx[2] + '</a> (' + bytes + ' ' + range + ')');
	$('.view .url', obj).html('<a class="link" href="' + dx[0] + '" target="_blank">' + dx[0] + '</a> ('+ bytes + ' ' + range + ')');
	$('.sample', obj).attr('src', photo);
//	$('.view .link', obj).mouseover(function() {
//	
//	}).mouseout(function() {
//		
//	});
	$('.view', obj).show();

	return false;
}
// ---------------------------------------------------------------------------------
function upload_return(data)
{
	for (id in data) {
		upload_done(id, data[id]);
	}
}
// ---------------------------------------------------------------------------------
function upload_delete(id)
{
	var obj = id instanceof jQuery ? id : $('#' + id);

	$('.view', obj).hide();
	$('.find', obj).val('').show();
	$('.data', obj).val('');

	return false;
}
// ---------------------------------------------------------------------------------
$(document).ready(function() {
	$('.upload').each(upload);
});
