$(document).ready(function(){
	var name = "aql_state";
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0){
			var state_model = c.substring(nameEQ.length,c.length);
			if(state_model.search('saved_')===0){
				var model = state_model.replace('saved_','');
				$('<div id = "'+model+'_message"><div class="aql_saved">Saved</div></div>').insertBefore($('form[name='+model+']'));
				var date = new Date();
				 document.cookie = name+"=1;expires=" + date.toGMTString() + ";path=/;";
			}
		}				
	}
});
$.skybox_form = function(model,ide,user_options,onSuccessFn) {
	var options = {
		model: model	
	};
	if($.isFunction(ide)){
		onSuccessFn = ide;
		ide = null;
	}else if(typeof(ide) == 'object'){
		user_options = ide;
		ide = null;
	}
	if($.isFunction(user_options)){
		onSuccessFn = user_options;
		user_options = null;	
	}
	$.extend(options, user_options);
	skybox('/aql/skybox-profile2/'+model+'/'+ide,options,options.width,options.height,onSuccessFn);
};
$.fn.skybox_form = function(model,ide,user_options,onSuccessFn) {
	if(user_options)
		user_options.selector = $(this).selector;
	return $.skybox_form(model,ide,user_options,onSuccessFn);
};
function delete_skybox_form(model, options, onSuccessFn) {
	var theform = $('form[name='+model+']:first, form[id='+model+'_form]');
	if(theform.length === 0){
		alert("save_skybox_form error: Could not find form.");
		return false;
	}
	var message_div = model + '_message';
	$('#'+message_div).remove();
	$('<div id ="'+message_div+'"/>').insertBefore(theform);
	$('#'+message_div).html("<img src = '/images/loading2.gif'/>");
	if (!onSuccessFn) {
		onSuccessFn = function (req) {
			if(options.uri){
				$(options.selector).load(decodeURIComponent(options.uri),function(data){
						if (options.onSuccessFn2)
							eval(options.onSuccessFn2);
				});
			}
			history.back();
		};
	}
	$.post('/aql/delete/' + model,$(theform).serialize(),function(data){
																		$('#'+message_div).html(data);
																		onSuccessFn(data);										
																	});
};
function save_form(model,options,new_href,onSuccessFn){
	var theform = $('form[name='+model+']:first, form[id='+model+'_form]');
	var silent = false;
	var onFailFn2 = null;
	var onSuccessFn2 = null;
	
	if(theform.length === 0){
		alert("save_skybox_form error: Could not find form.");
		return false;
	}
	if(options){
		if(typeof options != "object"){
			onSuccessFn = new_href;
			new_href = options;
			options = null;
		} else {
			silent = options.silent?options.silent:false;
			onSuccessFn2 = options.onSuccessFn2?options.onSuccessFn2:null;
			onFailFn2 = options.onFailFn2?options.onFailFn2:null;
		}
	}
	if($.isFunction( new_href )){
		onSuccessFn = new_href;
		new_href = false;
	}
	var message_div = model + '_message';
	$('#'+message_div).remove();
	$('<div id ="'+message_div+'"/>').insertBefore(theform);
	if(!silent){
		$('#'+message_div).html("<img src = '/images/loading2.gif'/>");
	}
	if (!onSuccessFn) {
		var onSuccessFn = function (data){
			if ( trimString(data).indexOf('<!--saved-->') != 0 ) {
					if(!silent){
						$( '#'+message_div ).html(data);
						$.scrollTo(0,1000);
					}
					if (onFailFn2)
						eval(onFailFn2);
				} else { 
					var needle = '<!--ide=';
					var start = data.indexOf(needle) + needle.length;
					var end = data.indexOf('-->',start);
					var ide = data.substring(start,end);
					if (ide) {
						var date = new Date();
						date.setTime(date.getTime()+600000);
						var expires = " expires="+date.toGMTString();
						document.cookie = 'aql_state'+"="+'saved_'+model+';'+expires+"; path=/";
						if(!new_href){
							// get the url up to /add-new
							start = 0;
							end = location.href.indexOf('/add-new');
							if ( end > -1 ) 
								new_href = location.href.substring(start,end); // profile page add new
							else new_href = location.href; // submit page add new
								location.href = new_href + '/' + ide;
						} else {
							location.href = new_href + '/' + ide;
						}
					} else {
						if(!silent){
							$( '#'+message_div ).html(data);
							$.scrollTo(0,1000);
							
						}
						if (onSuccessFn2)
							eval(onSuccessFn2);
					}
				}
		}
	}
	if ( $('span.mceEditor').length ) {
		tinyMCE.triggerSave();
    }
	$.post('/aql/save/' + model,$(theform).serialize(),function(data){
														onSuccessFn(data);										
													});
};//function

function save_skybox_form( model,options,onSuccessFn,onSuccessFn2 ) {
	var theform = $('form[name='+model+']:first, form[id='+model+'_form]');
	if(theform.length === 0){
		alert("save_skybox_form error: Could not find form.");
		return false;
	}
	var message_div = model + '_message';
	$('#'+message_div).remove();
	$('<div id ="'+message_div+'"/>').insertBefore(theform);
	$('#'+message_div).html("<img src = '/images/loading2.gif'/>");
	if (!onSuccessFn) {
		var onSuccessFn = function (data){
			if ( trimString(data).indexOf('<!--saved-->') != 0 ) {
					$( '#'+message_div ).html(data);
					$.scrollTo(0,1000);
				} else { 
					var needle = '<!--ide=';
					var start = data.indexOf(needle) + needle.length;
					var end = data.indexOf('-->',start);
					var ide = data.substring(start,end);
					$( '#skybox' ).html(data);
					var refresh_divFn = function () {
						if(options.uri){
							$(options.selector).load(decodeURIComponent(options.uri),function(data){
									if (onSuccessFn2)
										eval(onSuccessFn2);
							});
						}else if(onSuccessFn2){
							eval(onSuccessFn2);
						}
						history.back();
					}
					setTimeout(refresh_divFn,750);
				}
		}
	}
	$.post('/aql/save/' + model,$(theform).serialize(),function(data){
															$('#'+message_div).html(data);
															onSuccessFn(data);										
														});

};//function
function save_primary_profile( form_id, model, onSuccessFn, onErrorFn ) {
	theform = document.getElementById(form_id);
	message_div = form_id + '_message';
	if (document.getElementById( message_div )) {
		document.getElementById( message_div ).innerHTML = '<img src="/images/loading2.gif" />';
	}
	if (!onSuccessFn) {
		onSuccessFn = function (req) {
			//alert(req.responseText);
			if ( req.responseText.indexOf('<!--saved-->')==0 ) {
				//alert(req.responseText);
				needle = '<!--ide=';
				start = req.responseText.indexOf(needle) + needle.length;
				end = req.responseText.indexOf('-->',start);
				ide = req.responseText.substring(start,end);
				if (ide) {
					// get the url up to /add-new
					start = 0;
					end = location.href.indexOf('/add-new');
					if ( end > -1 ) new_href = location.href.substring(start,end); // profile page add new
					else new_href = location.href; // submit page add new
					location.href = new_href + '/' + ide;
				} else {
					document.getElementById( message_div ).innerHTML = req.responseText;
					$.scrollTo(0,1000);
				}
			} else if (document.getElementById( message_div )) {
				document.getElementById( message_div ).innerHTML = req.responseText;
				$.scrollTo(0,1000);
			}
//			window.scrollTo(0,0);
		};
	}
	if (!onErrorFn) {
		onErrorFn = function (req) {
			alert('There has been an error. Check your form action.');
		};
	}
	theform.method = 'post';
	theform.action = '/aql/save/' + model;
	AjaxRequest.submit(theform,{
		'aql_save' : location.href,
		'onSuccess' : onSuccessFn,
		'onError' : onErrorFn
	});	
}//function


function save_web_request_form( form_id, model, new_href, onSuccessFn, onErrorFn ) {
	theform = document.getElementById(form_id);
	message_div = form_id + '_message';
	if (document.getElementById( message_div )) {
		document.getElementById( message_div ).innerHTML = '<img src="/images/loading2.gif" />';
	}
	if (!onSuccessFn) {
		onSuccessFn = function (req) {
			//alert(req.responseText);
			start = new_href.length - 1;
			end = new_href.length;
			if ( new_href.substring(start,end) == '/' ) new_href = new_href.substring(0,start);
			if ( req.responseText.indexOf('<!--saved-->')==0 ) {
				needle = '<!--ide=';
				start = req.responseText.indexOf(needle) + needle.length;
				end = req.responseText.indexOf('-->',start);
//				alert(start);
//				alert(end);
//				alert(req.responseText);
				if (end > start) {
					ide = req.responseText.substring(start,end);
					if (new_href) location.href = new_href + '/' + ide;
					else location.href = location.href + '/' + ide;
				} else location.href = new_href;				
			} else if (document.getElementById( message_div )) {
				document.getElementById( message_div ).innerHTML = req.responseText;
				$.scrollTo(0,1000);
			}
			//window.scrollTo(0,0);
		};
	}
	if (!onErrorFn) {
		onErrorFn = function (req) {
			alert('There has been an error. Check your form action.');
		};
	}

	theform.method = 'post';
	theform.action = '/aql/save/' + model;
	AjaxRequest.submit(theform,{
		'aql_save' : location.href,
		'onSuccess' : onSuccessFn,
		'onError' : onErrorFn
	});	
}//function

function open_skybox_profile(title,model,ide,qs,div,refresh_uri,width,onSuccessFunction,onSuccessFunction2) {
	if ( !width ) width = 500;
//	alert( '/aql/skybox-profile/'+model+'/'+ide+'?'+qs+'&title='+title+'&div_id='+div+'&refresh_uri='+refresh_uri );
	skybox('/aql/skybox-profile/'+model+'/'+ide+'?'+qs+'&title='+title+'&div_id='+div+'&refresh_uri='+refresh_uri+'&onSuccessFn='+onSuccessFunction2,width,false,onSuccessFunction);
}

function profile_remove(model,ide,div_id,refresh_div_uri) {
	document.getElementById(div_id).innerHTML = '<img src="/images/loading2.gif" />';
	AjaxRequest.post({
		'url' : '/aql/delete/' + model,
		'ide' : ide,
		'onSuccess':function(req){
			// refresh the 1-to-m module on the profile page
			AjaxRequest.post({
				'url' : refresh_div_uri,
				'onSuccess':function(req){
					document.getElementById(div_id).innerHTML = req.responseText;
				}
			});	
		}
	});	
}

function save_skybox_profile( form_id, model, underlying_div, refresh_uri, onSuccessFn, onErrorFn, onSuccessFn2 ) {
	theform = document.getElementById(form_id);
	message_div = form_id + '_message';
	if (document.getElementById( message_div )) {
		document.getElementById( message_div ).innerHTML = '<img src="/images/loading2.gif" />';
	}
	if (!onSuccessFn) {
		onSuccessFn = function (req) {
			if ( trimString(req.responseText).indexOf('<!--saved-->') != 0 ) {
				document.getElementById( message_div ).innerHTML = req.responseText;
			} else { 
				document.getElementById( 'skybox' ).innerHTML = req.responseText;
				refresh_divFn = function () {
					AjaxRequest.post({
						'url' : decodeURIComponent(refresh_uri),
						'onSuccess':function(req){
							document.getElementById(underlying_div).innerHTML = req.responseText;
							if (onSuccessFn2) onSuccessFn2();
							history.back();
						}
					});
				}
				setTimeout(refresh_divFn,750);
			}//if
		};
	}
	if (!onErrorFn) {
		onErrorFn = function (req) {
			alert('There has been an error. Check your form action.');
		};
	}

	theform.method = 'post';
	theform.action = '/aql/save/' + model;
	AjaxRequest.submit(theform,{
		'aql_save' : location.href,
		'onSuccess' : onSuccessFn,
		'onError' : onErrorFn
	});	
}//function

function delete_skybox_profile( form_id, model, underlying_div, refresh_uri, onSuccessFn, onErrorFn ) {
	theform = document.getElementById(form_id);
	message_div = form_id + '_message';
	if (document.getElementById( message_div )) {
		document.getElementById( message_div ).innerHTML = '<img src="/images/loading2.gif" />';
	}
	if (!onSuccessFn) {
		onSuccessFn = function (req) {
			//alert(req.responseText);
			AjaxRequest.post({
				'url' : refresh_uri,
				'onSuccess':function(req){
					document.getElementById(underlying_div).innerHTML = req.responseText;
					history.back();
				}
			});
		};
	}
	if (!onErrorFn) {
		onErrorFn = function (req) {
			alert('There has been an error. Check your form action.');
		};
	}

	theform.method = 'post';
	theform.action = '/aql/delete/' + model;
	AjaxRequest.submit(theform,{
		'aql_save' : location.href,
		'onSuccess' : onSuccessFn,
		'onError' : onErrorFn
	});	
}//function


function aql_grid(grid_id,param) {
	eval("json_e = grid_e_"+grid_id+";");
	AjaxRequest.post({
		'url' : '/aql/grid',
		'grid' : json_e,
		'onSuccess':function(req){
			document.getElementById("grid_"+grid_id).innerHTML = req.responseText;
		}
	});
}//function aql_grid()


function save_grid_row( form_id, model, onSuccessFn, onErrorFn ) {
	theform = document.getElementById(form_id);
	message_div = form_id + '_message';
	if (document.getElementById( message_div )) {
		document.getElementById( message_div ).innerHTML = '<img src="/images/loading2.gif" />';
	}
	if (!onSuccessFn) {
		onSuccessFn = function (req) {
			//alert(req.responseText);
			document.getElementById( message_div ).innerHTML = req.responseText;
		};
	}
	if (!onErrorFn) {
		onErrorFn = function (req) {
			alert('There has been an error. Check your form action.');
		};
	}
	theform.method = 'post';
	theform.action = '/aql/save/' + model;
	AjaxRequest.submit(theform,{
		'aql_save' : location.href,
		'onSuccess' : onSuccessFn,
		'onError' : onErrorFn
	});	
}//function

function aql_archive(ide,model) {
	AjaxRequest.post({
		'url' : '/aql/archive/'+model,
		'ide' : ide,
		'onSuccess':function(req){
			document.getElementById('aql_archive_'+ide).innerHTML = req.responseText;
		}
	});
}//function

function aql_delete(ide,model,successFunc) {
	AjaxRequest.post({
		'url' : '/aql/delete/'+model,
		'ide' : ide,
                'primary_table' : model,
		'onSuccess': successFunc || function(req){
			document.getElementById('aql_delete_'+ide).innerHTML = req.responseText;
		}
	});
}//function

