
var subs = {};
$(document).ready(function(){	
	$.ajax({
		url: "app/model/SetupSubscriptions.php",
		success: function(result) {
			subs.Load(result);
		}
	});
});

subs.GetModal = function(post_data , callback){
	$.ajax({
		url: "app/model/SetupSubscriptions.php",
		data : post_data,
		type : "POST",
		success: function(result) {
			var data = ui.ParseJSON(result);
			if(data["Status"] == "Success"){
				callback(result);
			}			
		}
	});
}

subs.Load = function(result){	
	data = ui.ParseJSON(result);	
	if (data.no_promo == "true") {
		cp.UpdateToggleButtons("Disabled", "display_upgrade");
	} else {
		cp.UpdateToggleButtons("Enabled", "display_upgrade");
	}

	$(".toggle button").on("click", function(e) {
		if ($(this).hasClass("enable_this")) {						
			subs.TogglePromo("false");
		} else {			
			subs.TogglePromo("true");

		}
	});

	subs.UI();
}

subs.TogglePromo = function(no_promo){
	$.ajax({
		url: "app/model/SetupSubscriptions.php?no_promo="+no_promo,		
		success: function(result) {
			var data = ui.ParseJSON(result);			
			if (data.no_promo == "true") {				
				cp.UpdateToggleButtons("Disabled", "display_upgrade");
			} else {
				cp.UpdateToggleButtons("Enabled", "display_upgrade");
			}		
		}
	});
}


subs.UI = function(){

	$("#Reports li").draggable({
		helper: 'clone',
		revert: "invalid"
	});	

	$(".btn[name='subsave#submit']").on("click", function(e){
		e.preventDefault(); // no! bad form! No posting!
		var data = FormObjectToArray( $(".new-sub-form form") );

		data['subsave#submit'] = true;
		subs.GetModal(data, function(result){
			cp.SetupSubscriptions();
			ui.Callout({ Status : "Success", Message : ui.data.languages["_SUCCESS_ADD_SUBSCRIPTION"] });
		});	
	});

	$(".delete-button").on("click", function(e){
		e.preventDefault(); // no! bad form! No posting!

		var name = $(this).attr("name");
		var data = FormObjectToArray( $(this).parents("form").first() );
		data.name = name;
		subs.GetModal(data, function(result){
			cp.SetupSubscriptions();
			ui.Callout({ Status : "Success", Message : ui.data.languages["_SUCCESS_DELETE_SUBSCRIPTION"] });
		});	
	});
		
	$(".btn[name='subedit#submit']").on("click", function(e){
		e.preventDefault(); // no! bad form! No posting!
		var data = FormObjectToArray( $(this).parents("form").first() );
		data['subedit#submit'] = true;
		subs.GetModal(data, function(result){
			cp.SetupSubscriptions();
			ui.Callout({ Status : "Success", Message : ui.data.languages["_SUCCESS_EDIT_SUBSCRIPTION"] });
		});
	});
		

	$('.subscription-settings button[data-widget="remove"]').on("click", function(){
		$(".subscription-settings").hide();
		$(".subscription-settings .custom-form").hide();
	});

	$(".subscriptioncontent li").draggable({ // Apply the draggable to reports in the subscriptions list
		helper: 'clone',
		revert: "invalid"
	});
	
	$("#Subscriptions > li").droppable({ // Make it possible to drop reports in the subscriptions list
		accept: "#Reports > li, .subscriptioncontent > li",
		drop: function(ev, ui) {

			var reportID = ui.draggable.attr('rel');

			if($(this).find(".subscriptioncontent").find("li[rel='" + reportID + "']").length >= 1) { // If the report already exists for this subcription, we don't want to do anything (the drag will be reverted)
				return false;
			}		
		
			$(this).addClass("open"); // Show the contents of the profile
				
			var cloned_object = ui.draggable.clone();			

			cloned_object.find(".subscription-color").remove();


			var subColor = $(this).find(".subscriptionname").attr("style");

			$("#Reports li[rel='"+ reportID +"']").append("<div class='subscription-color' style='"+ subColor +"'></div>");

			
			cloned_object.prependTo($(this).find(".subscriptioncontent")); // Prepend the cloned object to the profile's list
			cloned_object.addClass('added'); // Add a CSS class so we know this is a to-be-added report.
			
			$(cloned_object).draggable({ // Reapply the draggable to the cloned object
				helper: 'clone',
				revert: "invalid"
			});
		}
	});
	
	$("#Reports").droppable({ // Make it possible to remove reports from the subscription
		accept: ".subscriptioncontent > li",
		drop: function(ev, ui) {
			ui.draggable.remove();
		}
	});
	
	$(".subscriptionname").on("click", function(ev) { // Show / Hide a subscription's content
		if($(this).next(".subscriptioncontent").is(":hidden") == true) {
			$(this).parent().addClass("open"); // Show the content
		} else {
			$(this).parent().removeClass("open"); // Hide the content
		}
	});
	
	$(".commit-install").on("click", function() {
		var subscriptions = {};
		$("#Subscriptions > li").each( function() {
			var subscr_id = $(this).find(".subscriptionname").attr("rel");
			var report_ids = [];
			
			var i = 0;
			$(this).find(".subscriptioncontent > li").each(function() {	
				report_ids[i] = $(this).attr("rel");
				i ++;
			});
			subscriptions['editsubscriptionReports'] = 'ok';
			subscriptions[subscr_id] = report_ids;
		});
		
		subs.GetModal(subscriptions, function(){
			cp.SetupSubscriptions();
		});	
	});
	
	
	
	$("#report-filter").keyup(function() { // Filter profiles by the user's input
		if($("#report-filter").val() != "") {
			$("#Reports .reportname").each(function() {
				if($(this).text().toLowerCase().indexOf($("#report-filter").val().toLowerCase()) >= 0) {
					$(this).parent().show();
					$(this).addClass("selected");
				} else {
					$(this).parent().hide();
					$(this).removeClass("selected");
				}
			});
			
			$(".all-reports").removeClass("selected");
		} else {
			$("#Reports > li").show();
			$("#Reports > li > .reportname").addClass("selected");
			$(".all-reports").addClass("selected");
		}
	});
	
	
	$(".add-new-sub").on("click", function() {
		$(".subscription-settings .custom-form").hide();
		$(".delete-subscription-form").hide();
		$(".subscription-settings .new-sub-form").show();
		$(".subscription-settings").show();
	});
	
	$(".edit-subscription").on("click", function() {
		$(".delete-subscription-form").hide();
		$(".subscription-settings .custom-form").hide();
		$(".subscription-settings .edit-sub-"+ $(this).attr("rel") ).show();
		$(".subscription-settings").show();
	});
	
	$(".copy-subscription").on("click", function() {
		var copy_from = $(this).attr("name");
		var new_sub = prompt("Copy Subscription '"+copy_from+"' To (New Name): ");
		
		if(new_sub == "" || new_sub == undefined){
			alert(ui.data.languages['_INVALID_SUBSCRIPTION_NAME']);
			return false;
		}
		
		var posting = {};
		posting["copy_from"] = copy_from;
		posting["copy_to"] = new_sub;

		subs.GetModal(posting, function(){
			cp.SetupSubscriptions();
			ui.Callout({ Status : "Success", Message : ui.data.languages["_SUCCESS_MADE_COPY"] });
		});

	});

	$(".default-subscription").on("click", function() {
		data = { "default_subscription" : $(this).attr("name") };
		subs.GetModal(data, function(){
			cp.SetupSubscriptions();
			ui.Callout({ Status : "Success", Message : ui.data.languages["_SUBSCRIPTION_MARKED_DEFAULT"] });
		});

	});
	
	$(".delete-subscription").on("click", function() {
		$(".subscription-settings .custom-form").hide();

		$(".delete-subscription-form .subscription_tag").html("("+$(this).attr("name")+")");
		$(".delete-subscription-form #subtodelete").attr("value", $(this).attr("rel") );
		
		$(".delete-subscription-form").show();
		$(".subscription-settings").show();
	});

	$(".cancel-reset").on("click", function(e){
		e.preventDefault();		

		$(".subscription-settings .delete-subscription-form").hide();
		$(".subscription-settings").hide();
	});

	$(".subscriptioncontent li").each( function(){
		var reportID = $(this).attr("rel");
		var subColor = $(this).parents("li").first().find(".subscriptionname").attr("style");

		$("#Reports li[rel='"+ reportID +"']").append("<div class='subscription-color' style='"+ subColor +"'></div>");

	});
}