// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//Change box profile page

app_timer="";
build_timer={};
deploy_timer={};
heroku_log="";

function profile_tabs(id, elem)
{
	$('#account_profile').hide();
	$('#public_profile').hide();
	$('#password_profile').hide();
	$('#payment_history').hide();
	$('#plans').hide();

	if(document.getElementById('link1') != null)document.getElementById('link1').className = "no_class";
	if(document.getElementById('link2') != null)document.getElementById('link2').className = "no_class";
	if(document.getElementById('link3') != null)document.getElementById('link3').className = "no_class";

	document.getElementById(elem).className = "selected";

    $("#"+id).show();
}
//show help modalbox
function show_modal(url)
{	
	tb_show('Getting Started with Projects', url+'?height=480&width=550','');
}

//show copied! hint then hide it
function show_hint(id)
{
	$("#copied_"+id).show();
	setTimeout(function() {$("#copied_"+id).hide()},3000)
}

//Show a modal box at the top of the page if you are visiting a modal box view
function show_modal_message(message, class_name)
{
	$('#'+class_name).remove();
	remove_me_dashboard()
	
	$('#TB_window').append("<div style='display:none' id='"+class_name+"'>"+message+"</div>");
	
	$('#'+class_name).prepend("<div style='float: right; width: 25px;'><a href='javascript:remove_me_dashboard()' class='delete_my_app'></a></div>")
	
	if($('#error').length == 0 && $('#modal_error').length == 0)
		$('#'+class_name).fadeIn(1000).delay(8000).fadeOut(400);
	else
		$('#'+class_name).fadeIn(1000)
	
	
	 // $('#'+class_name).fadeIn(400).delay(7000).fadeOut(800);
}

function remove_me_dashboard()
{
	$('#error').remove();
	$('#modal_error').remove();
	$('#modal_success').remove();
	$('#flash_message').remove();
	$('#success_dashboard').remove();
	$('#error_dashboard').remove();
	$('#success').remove();
}

//Show a modal box at the top of the page if you are visiting the dashboard
function show_modal_dashboard_message(message, class_name)
{
	$('#'+class_name).remove();
	remove_me_dashboard()
	
	$('#banner').append("<div style='display:none' id='"+class_name+"'>"+message+"</div>");
	$('#'+class_name).prepend("<div style='float: right; width: 25px;'><a href='javascript:remove_me_dashboard()' class='delete_my_app'></a></div>")
	
	if($('#error_dashboard').length == 0)
		$('#'+class_name).fadeIn(1000).delay(8000).fadeOut(400);
	else
		$('#'+class_name).fadeIn(1000)
	
}

//Unblock the app in the dashboard
function finish_job(id)
{
	$('#loading_'+id).hide();
	$('#app_cover_'+id).hide();	
	$('#finish_'+id).hide();
	$("#app_box_"+id).highlightFade('yellow');
	$("body a.thickbox").unbind();
	tb_init($("body a.thickbox"));
}

//Block the app in the dashboard
function block_app(id, message)
{
	$('#app_parent_'+id).prepend("<div id='loading_"+id+"' class='loading'><img src='/images/loading.gif'> App is being "+message+", please wait.</div>");
	$('#app_parent_'+id).prepend("<div class='app_cover' id='app_cover_"+id+"'></div>");
}

function hide_show_help()
{
	if($('#help_container'+':visible').length > 0) $('#help_container').fadeOut(200);
	else $('#help_container').fadeIn(200);
}
//show Hide project
function change_project_status(id)
{
	if($('#box_'+id+':visible').length > 0) $('#box_'+id).fadeOut(200);
	else	$('#box_'+id).fadeIn(200);
	$('#arrow_'+id).toggleClass("drop_down drop_up");
}
function search_project(text)
{
	if(text.length > 2)
	{	
		$('#my_list_of_apps .project_container').each(function(index,value){$(value).hide()})
		$("h3:contains("+text+")").each(
			function(index,value){
			
				$(value).parent().parent().parent().parent().parent().parent().parent().parent().parent().show();
			});
	}
	else
	{
		$('#my_list_of_apps .project_container').each(function(index,value){$(value).show()})	
	}
}
//show Hide project collaborators
function change_col_status(id)
{
	if($('#full_list_'+id+':visible').length > 0)
		$('#full_list_'+id).fadeOut();
	else
		$('#full_list_'+id).fadeIn();
	
	$('#col_arrow_'+id).toggleClass("drop_down drop_up");
}
//Gets the new Observers to open modal boxes
function re_init()
{
	// tb_init($("#app_box_"+id+" a.thickbox"));
	$("body a.thickbox").unbind();
	tb_init($("body a.thickbox"));
}

//Change the Lock image to Unlock image and viseversa
function change_status(id)
{
	$('#'+id).toggleClass("app_private app_public");
}
// _____________________________________________________________________________________________________________
// deploy jobs ajax
// _____________________________________________________________________________________________________________
function do_undeploy(id)
{
	$.ajax({ url: "/apps/"+id+"/undeploys",
	type: "POST",
	data: "app_id="+id
});
}
function confirm_undeploy(id)
{

	jConfirm('Are you sure? Undeploy will stop your application and remove the redis database.', 'RhoHub', function(r) {
		if(r)
		{
			block_submit();
			do_undeploy(id);
		}
	});
}
function check_deploy_state(pending_deploys)
{
	if(pending_deploys=="true")block_submit();
}
function block_submit(){
	$('#deploy').disable();
	$('#deploy').toggleClass("deploy deploy_block");

	$('#undeploy').disable();
	$('#undeploy').toggleClass("undeploy undeploy_block");
}
function unblock_submit(){
	$('#deploy').enable();
	$('#deploy').toggleClass("deploy_block deploy");
}
function check_deploy_jobs(id)
{
	deploy_timer[id] = setInterval(function() {
		if(deploy_timer[id]!="stop")
		 check_for_deploy_finished_job(id);
	 },5000);
}

function check_for_deploy_finished_job(id)
{
	$.ajax({ url: "/apps/"+id+"/deploys/check_jobs",
	type: "GET",
	data: "app_id="+id,
	success: function(result){
		if(result == "stop")
		{
			clearInterval(deploy_timer[id]);
			deploy_timer[id] = "stop";
		}
		else
		{
			if(result.split(",")[1] == "true")
			{
			update_deploys(result.split(",")[0]);
			update_an_app(id);
			}
		}
	}
});
}

function update_deploys(id)
{
	$.ajax({ url: "/apps/"+id+"/deploys/update_deploys",
	type: "GET",
	data: "app_id="+id
});
}
// _____________________________________________________________________________________________________________
// HeroKu job ajax
// _____________________________________________________________________________________________________________

function check_heroku_logs_jobs(id)
{
	$('#heroku_logs').html("Please wait loading heroku logs...")
	clearInterval(heroku_log);
	heroku_log = setInterval(function() { check_for_heroku_finished_job(id); },5000);	
}

function stop_heroku_log()
{
	clearInterval(heroku_log);
}

function check_for_heroku_finished_job(id)
{
	$.ajax({ url: "/apps/"+id+"/check_heroku_job",
	type: "GET",
	data: "app_id="+id,
	success: function(result){
		if(result == "stop")
		{
			clearInterval(heroku_log);
		}
	}
});		
}
// _____________________________________________________________________________________________________________
// build jobs ajax
// _____________________________________________________________________________________________________________

function check_build_jobs(id)
{
	build_timer[id] = setInterval(function() {
		if(build_timer[id]!="stop") 
		check_for_build_finished_job(id); 
		},7000);
}

function check_for_build_finished_job(id)
{
	$.ajax({ url: "/builds/check_jobs",
	type: "GET",
	data: "app_id="+id,
	success: function(result){
		if(result == "stop")
		{
			clearInterval(build_timer[id]);
			build_timer[id]="stop"
		}
		else
		{
			if(result.split(",")[1] == "true")
			{
			update_builds(result.split(",")[0]);
			update_an_app(id);
			}
		}
	}
});
}

function update_builds(id)
{
	$.ajax({ url: "/apps/"+id+"/builds/update_builds",
	type: "GET",
	data: "id="+id
});
}
// _____________________________________________________________________________________________________________
// App jobs ajax
// _____________________________________________________________________________________________________________

function check_app_jobs()
{
	app_timer = setInterval(function() {
		if(app_timer !="stop") 
		check_for_app_finished_job(); 
		},3000);
}

function check_for_app_finished_job()
{
	$.ajax({ url: "/apps/check_jobs",
	type: "GET",
	success: function(result){
		if(result == "stop")
		{
			clearInterval(app_timer);
			app_timer ="stop";
		}
		else
		$.each(result.split(','), function(index, value) {
			if(value.split('-')[0] == "delete")
			{	
				delete_project_error(value.split('-')[1])
			}
			else
			{
				if(value.split('-')[1] == "completed")
				update_an_app(value.split('-')[0])
			}
		});	
	}
});
}
function update_an_app(id)
{
	$.ajax({ url: "/apps/"+id+"/update_an_app",
	type: "GET",
	data: "id="+id
});
}
// _____________________________________________________________________________________________________________
// Application ajax
// _____________________________________________________________________________________________________________
function assign_resource_app(confirmation,id)
{
	if(confirmation)
	{
		$.ajax({ url: "/apps/"+id+"/assing_resources",
		type: "GET",
		data: "id="+id
	});
}
}
function restart_app(confirmation,id)
{
	if(confirmation)
	{
		$.ajax({ url: "/apps/"+id+"/restart_app",
		type: "GET",
		data: "id="+id
	});
}
}
function delete_project(confirmation,id)
{
	if(confirmation)
	{
		$.ajax({ url: "/projects/"+id,
		type: "DELETE",
		data: "id="+id
	});
}
}

function delete_project_error(id)
{
	$.ajax({ url: "/projects/"+id+"/project_error",
	type: "DELETE",
	data: "id="+id
});
}

function update_collaborator(role,id)
{
	$.ajax({ url: "/collaborators/"+id,
	type: "PUT",
	data: "role="+role+"&id="+id,
	beforeSend:function(){
		$('#spin_'+id).show();
	},
	success: function(){
		$('#spin_'+id).hide();
	}
});
}

function change_app_permissions(confirmation, id)
{
	if(confirmation)
	{
		$.ajax({ url: "/apps/"+id+"/change_app_permissions",
		type: "POST",
		data: "id="+id,
		beforeSend:function(){
			$('#spin_app_'+id).show();
		},
		success: function(){
			$('#spin_app_'+id).hide();
		}
	});
}
}

function delete_app(confirmation,id)
{
	if(confirmation)
	{
		$.ajax({ url: "/apps/"+id,
		type: "DELETE",
		data: "id="+id,
		beforeSend:function(){
			$('#spin_app_'+id).show();
		},
		success: function(){
			$('#spin_app_'+id).hide();
		}
	});
}
}

// _____________________________________________________________________________________________________________
// jQuery Effects
// _____________________________________________________________________________________________________________
function runHideEffect(title)
{
	$("#"+title).blindToggle('fast');
}

function runEffect(title)
{
	$("#box_"+title).blindToggle('fast');
}

jQuery.fn.blindToggle = function(speed, easing, callback)
{
	return this.animate({marginTop: parseInt(this.css('marginTop')) < 0 ? 0 : -130}, speed, easing, callback);  
};

jQuery.fn.highlightFade = function(settings) {
	var o = (settings && settings.constructor == String) ? {start: settings} : settings || {};
	var d = jQuery.highlightFade.defaults;
	var i = o['interval'] || d['interval'];
	var a = o['attr'] || d['attr'];
	var ts = {
		'linear': function(s,e,t,c) { return parseInt(s+(c/t)*(e-s)); },
		'sinusoidal': function(s,e,t,c) { return parseInt(s+Math.sin(((c/t)*90)*(Math.PI/180))*(e-s)); },
		'exponential': function(s,e,t,c) { return parseInt(s+(Math.pow(c/t,2))*(e-s)); }
	};
	var t = (o['iterator'] && o['iterator'].constructor == Function) ? o['iterator'] : ts[o['iterator']] || ts[d['iterator']] || ts['linear'];
	if (d['iterator'] && d['iterator'].constructor == Function) t = d['iterator'];
	return this.each(function() {
		if (!this.highlighting) this.highlighting = {};
		var e = (this.highlighting[a]) ? this.highlighting[a].end : jQuery.highlightFade.getBaseValue(this,a) || [255,255,255];
		var c = jQuery.highlightFade.getRGB(o['start'] || o['colour'] || o['color'] || d['start'] || [255,255,128]);
		var s = jQuery.speed(o['speed'] || d['speed']);
		var r = o['final'] || (this.highlighting[a] && this.highlighting[a].orig) ? this.highlighting[a].orig : jQuery.curCSS(this,a);
		if (o['end'] || d['end']) r = jQuery.highlightFade.asRGBString(e = jQuery.highlightFade.getRGB(o['end'] || d['end']));
		if (typeof o['final'] != 'undefined') r = o['final'];
		if (this.highlighting[a] && this.highlighting[a].timer) window.clearInterval(this.highlighting[a].timer);
		this.highlighting[a] = { steps: ((s.duration) / i), interval: i, currentStep: 0, start: c, end: e, orig: r, attr: a };
		jQuery.highlightFade(this,a,o['complete'],t);
	});
};

jQuery.highlightFade = function(e,a,o,t) {
	e.highlighting[a].timer = window.setInterval(function() { 
		var newR = t(e.highlighting[a].start[0],e.highlighting[a].end[0],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newG = t(e.highlighting[a].start[1],e.highlighting[a].end[1],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newB = t(e.highlighting[a].start[2],e.highlighting[a].end[2],e.highlighting[a].steps,e.highlighting[a].currentStep);
		jQuery(e).css(a,jQuery.highlightFade.asRGBString([newR,newG,newB]));
		if (e.highlighting[a].currentStep++ >= e.highlighting[a].steps) {
			jQuery(e).css(a,e.highlighting[a].orig || '');
			window.clearInterval(e.highlighting[a].timer);
			e.highlighting[a] = null;
			if (o && o.constructor == Function) o.call(e);
		}
		},e.highlighting[a].interval);
	};

	jQuery.highlightFade.defaults = {
		start: [255,255,128],
		interval: 50,
		speed: 400,
		attr: 'backgroundColor'
	};

	jQuery.highlightFade.getRGB = function(c,d) {
		var result;
		if (c && c.constructor == Array && c.length == 3) return c;
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))
		return [parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];
		else if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))
		return [parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];
		else if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))
		return [parseInt("0x" + result[1]),parseInt("0x" + result[2]),parseInt("0x" + result[3])];
		else if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))
		return [parseInt("0x"+ result[1] + result[1]),parseInt("0x" + result[2] + result[2]),parseInt("0x" + result[3] + result[3])];
		else
		return jQuery.highlightFade.checkColorName(c) || d || null;
	};

	jQuery.highlightFade.asRGBString = function(a) {
		return "rgb(" + a.join(",") + ")";
	};

	jQuery.highlightFade.getBaseValue = function(e,a,b) {
		var s, t;
		b = b || false;
		t = a = a || jQuery.highlightFade.defaults['attr'];
		do {
			s = jQuery(e).css(t || 'backgroundColor');
			if ((s  != '' && s != 'transparent') || (e.tagName.toLowerCase() == "body") || (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end)) break; 
			t = false;
			} while (e = e.parentNode);
			if (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end) s = e.highlighting[a].end;
			if (s == undefined || s == '' || s == 'transparent') s = [255,255,255];
			return jQuery.highlightFade.getRGB(s);
		};

		jQuery.highlightFade.checkColorName = function(c) {
			if (!c) return null;
			switch(c.replace(/^\s*|\s*$/g,'').toLowerCase()) {
				case 'aqua': return [0,255,255];
				case 'black': return [0,0,0];
				case 'blue': return [0,0,255];
				case 'fuchsia': return [255,0,255];
				case 'gray': return [128,128,128];
				case 'green': return [0,128,0];
				case 'lime': return [0,255,0];
				case 'maroon': return [128,0,0];
				case 'navy': return [0,0,128];
				case 'olive': return [128,128,0];
				case 'purple': return [128,0,128];
				case 'red': return [255,0,0];
				case 'silver': return [192,192,192];
				case 'teal': return [0,128,128];
				case 'white': return [255,255,255];
				case 'yellow': return [255,255,0];
			}
		};
