/**
 * Support
 */

var Support = Support || { };

Support.Designs = {

	

	setup : function() {

		// var $customization = $("#site_customization");

		// this.populate();

		// // If we're filtering, hide the nav
		// if ( Cargo.Helper.GetActiveFilter() !== '' ) {
		// 	$('#site_customization').hide();
		// }

		// // Toggle
		// $('.designs_title > span').on('click', function() {
		// 	$customization.toggleClass('active');
		// });

	}

};

Support.DesignFilter = {

	Data : {
		'customization_id' : 7418304,
		'template' 	: '',
		'set'		: ''
	},

	/**
	 * Init
	 */
	setup : function() {
		this.Data.site_design_container = $('<div/>').addClass('active_design');
		this.Data.design_chooser = $('<div/>').addClass('design_chooser');
		this.Data.set = $('div[data-setid="'+this.Data.customization_id+'"]');
	},

	/**
	 * Run all the filtering things
	 */
	doFilter : function() {
		// Add the current site and design marker
		this.addSiteAndDesign();

		// Filter the topics for this design
		if(!Cargo.Helper.IsFilter()) {
			this.filterTopics();
		}

		// Add the design dropdown
		this.populateDesignList();
		
	},

	/**
	 * Populate the design list drop down
	 */
	populateDesignList : function() {
		var template   = '<div class="design"><a href="/support-new/filter/%DESIGN_ID%"><span>%DESIGN_NAME%</span></a></div>'

		this.Data.design_chooser
			.appendTo($('.set_title_thumbnails', this.Data.set));

		for(var i=0; i<Support.Site.Data.design_list.length; i++) {
			var design = template.replace(/%DESIGN_ID%/g, Support.Site.Data.design_list[i].id).replace(/%DESIGN_NAME%/g, Support.Site.Data.design_list[i].name);
			this.Data.design_chooser.append(design);
		}

	},

	/**
	 * Show the site and design messsage
	 */
	addSiteAndDesign: function() {
		var link   = Support.Site.Data.site_link;
		var site   = Support.Site.Data.site_name;
		var design = Support.Site.Data.site_design;

		// Add the 
		this.Data.site_design_container
			.html('You’re currently logged into <a href="' + link + '" target="_blank">' + site + '</a> which is running on the <span>' + design + '</span> design:')
			.appendTo($('.set_title_thumbnails', this.Data.set));

	},

	/**
	 * Filter the site customization topics based on design
	 */
	filterTopics : function() {
		var filter = Support.Site.Data.site_design;
		
		var filterCap = filter.charAt(0).toUpperCase() + filter.slice(1);
		
		// Hide all of em
		this.Data.set.find('.project_thumb[data-filters]').hide();

		// Show things for everyone
		this.Data.set.find('.project_thumb[data-filters~="all"]').show();

		// Show developer or legacy
		if(Support.Site.Data.site_is_developer_design) {
			this.Data.set.find('.project_thumb[data-filters~="developer"]').show();
		} else {
			this.Data.set.find('.project_thumb[data-filters~="legacy"]').show();
		}

		// Show all topics for this design
		this.Data.set.find('.project_thumb[data-filters~="' + filter + '"]').show();
	}

};

Support.Site = {

	Data : {
		site_link 				: null,
		site_name 				: null,
		site_design 			: null,
		site_parent_design		: null,
		site_is_developer_design: false,
		site_desk_design 		: null,
		site_template 			: null,
		design_list 			: null,
		filter 					: null,

	},

	setup  : function() {

		 $.ajax({
			url : "http://"+Cargo.Helper.GetBaseCargoDomain()+"/dispatch/support/getCargoSiteAndDesign/?callback=?",
			dataType : "jsonp",
			timeout: 2500,
			success : Support.Site.SiteAndDesignReturn 
		 });

		Cargo.Core.ReplaceLoadingAnims.init();
		
		// Create a form view, if there is one
		this.FormSubmit = new Cargo.View.FormSubmit({
			el : '.container form'
		});

	},

	/**
	 * When the setup calls for the logged in member's data, this
	 * is the callback
	 * @param {[type]} dataObj [description]
	 */
	SiteAndDesignReturn: function(dataObj) {

		if(dataObj.error.length == 0) {

			// Set site data
			Support.Site.Data.site_link 				= dataObj.jdata.site_link;
			Support.Site.Data.site_name 				= dataObj.jdata.site_name;
			Support.Site.Data.site_design 				= dataObj.jdata.site_design;
			Support.Site.Data.site_parent_design 		= dataObj.jdata.site_parent_design;
			Support.Site.Data.site_is_developer_design 	= dataObj.jdata.site_is_developer_design;
			Support.Site.Data.site_desk_design 			= dataObj.jdata.site_desk_design;
			Support.Site.Data.site_template 			= dataObj.jdata.site_template;
			Support.Site.Data.design_list 				= dataObj.jdata.design_list;

			// Set the filter
			Support.Site.Data.filter = Cargo.Helper.GetActiveFilter();

			if ( Support.Site.Data.filter == '' ) {
				Support.Site.Data.filter = Support.Site.Data.site_design;
			}

			Cargo.Event.trigger("support:loaded");
		}


	},

	setDesignFilter : function() {

		// Grab the active filter
		var filter = Support.Site.Data.filter;

		if ( filter !== '' ) {

			var filter = filter.toLowerCase();

			$('.project_content [data-filters]').hide();
			$('.project_content [data-filters*="' + filter + '"]').show();

			if ( $('.project_content [data-filters]:visible').length <= 0 ) {
				$('.project_content [data-filters*="polaris"]').show();
			}

		} else {
			
		}

	},

	checkSetVisibility: function() {
		// Find the active set based on the project ID
		var parentSet = $("[data-setid='" + Cargo.Model.Project.GetSetId() + "']"),
			otherSets = $("[data-setid]").not(parentSet);

		// If the set exists, set active/inactive
		if (parentSet.length > 0) {
			otherSets.removeClass("active").addClass("inactive");
			parentSet.removeClass("inactive").addClass("active");

			// Show the footer link
			$(".set_footer").show();
		} else {
			$(".set_footer").hide();
		}
	},

	

};

/**
 * The format of the projects
 * @type {Object}
 */
Support.Site.Project = {

	/**
	 * Render all on load complete
	 */
	LoadComplete: function() {
		Support.Site.Project.removeBrInSections();
		Support.Site.Project.FormatProject();
		Support.Site.Project.CodeTags();
		Support.Site.Project.CustomUrlSection();
	},
	/**
	 * Re-render the markup with parsed and formated code
	 * inside of the <pre> tag and re-render it
	 */
	FormatProject: function() {
		var markup = Cargo.Model.Project.GetContent2x();
		markup = this.FormatPreCode(markup);
		markup = this.RemoveSectionSplits(markup);

		$(".project_content").html(markup);
	},

	/**
	 * Strip all <br> and change chevrons to htmlencoded chars inside <pre>
	 * @param {String} markup The formated markup
	 */
	FormatPreCode : function(markup) {

		var re = /<pre[^>]*>([\s\S]*?)<\/pre>/gmi;
		var pieces = markup.match(re);
		
		if(pieces && pieces.length > 0) {
			for(i=0;i<pieces.length;i++) {
				var piece = pieces[i];
				var pre = piece.match(/(<pre[^>]*>)/)[0];
				var code = piece.match(/<pre[^>]*>([\s\S]*?)<\/pre>/)[1];
				var end_pre = "</pre>";

				// Remove all the breaks
				code = code.replace(/[<]br[^>]*[>]/gi,"");

				// start video tags with [video= instead of {video= to prevent Cargo from saving it
				// as a rendered object tag
				code = code.replace(/[\[]video=/gi, '{video=');

				// replace disabled chevrons
				code = code.replace(/(_&lt;_)/gi,"&lt;");
				code = code.replace(/(_&gt;_)/gi,"&gt;");

				// replace regular chevrons
				code = code.replace(/</gi,"&lt;");
				code = code.replace(/>/gi,"&gt;");

				markup = markup.replace(piece, pre + code + end_pre);

			}
		}

		return markup;
	},

	RemoveSectionSplits: function(markup) {
		var search = /<\/section>([\s\S]*?)<section/gmi;
		var replace = '</section><section';
		return markup.replace(search, replace);
	},

	/**
	 * Make the pretty print code tags work
	 */
	CodeTags : function() {

		// Escape the code tag
		$("code[data-code]").each(function() {
		  $(this).text($(this).attr("data-code"));
		});

		// Hack
		$("pre").each(function(i) {
			// add some classes for prettyPrinting
			var type = $(this).attr('data-lang');
			$(this).addClass('prettyprint lang-' + type);

		});
	
		prettyPrint();
	},

	CustomUrlSection: function() {
		$('.host_selection a').click(function() {
			var which = $(this).attr("href").replace("#", "");
			$('.host_selection a').removeClass('active');
			$("section").hide();
			$("section#"+which).show();
			$(this).addClass('active');

			var anchor_point = $('.host_selection').offset().top;
			if($(window).scrollTop() < (anchor_point - 50)) {
				window.scrollTo(0, anchor_point - 50);		
				$('html, body').animate({scrollTop: anchor_point }, 50);
			}
			
			return false;
		});

		$('section img').each(function() {
			
			if(!$(this).parent().hasClass("browser_chrome")) {
				$(this).wrap('<div class="browser_chrome"></div>').prepend('hello');
				var buttons = '<div class="block"><div class="featured_site_buttons"><div class="chrome_button close"></div><div class="chrome_button minimize"></div><div class="chrome_button full"></div></div></div>';
				$(this).before(buttons);
			}
		});
		
	},

	removeBrInSections: function() {
		var content = $(".project_content").html();
		var stripped = content.replace(/<\/section>[\s\S]*?<section/g, '</section><section');
		$(".project_content").html(stripped);
	}
}


/**
 * Backbone collection for search results
 * This collection will search desk for a keyword when it is fetched
 */
// Cargo.o.collection.searchdesk =  Backbone.Collection.extend({
// 	url	: function() {
// 		var term = (this.options && this.options.term) ? this.options.term : false;
// 		return '/dispatch/support/searchDesk/' + Cargo.API.Config.search_term;
// 	},

// 	fetch : function(options) {         
// 		this.options = options;
// 		Backbone.Model.prototype.fetch.apply(this, arguments);    
// 	}
	
// });

/**
 * Backbone view for search results
 * This view will fetch the search results for both
 * Cargo and Desk. They will be printed to the page once they
 * have been received. When they both are complete, the loading 
 * animations will complete
 */
Cargo.o.view.SearchResults = Backbone.View.extend({
	Data : {
		markup_cargo: null,
		// markup_desk: null,
	},

	/* Must have an initialize function */
	initialize: function(options) {
		this.options = options;

		this.options.template = 'SearchResults';
		this.options.dataset = 'search';

		this.cargo_collection = new Cargo.o.collection.search();
		// this.desk_collection = new Cargo.o.collection.searchdesk();
		this.cargo_collection.fetch();
		// this.desk_collection.fetch();

		/* Set an event to wait for the model to change */
		this.listenTo(this.cargo_collection, "reset", this.RenderCargo);
		this.listenTo(this.cargo_collection, "add", this.RenderCargo);

		// this.listenTo(this.desk_collection, "reset", this.RenderDesk);
		// this.listenTo(this.desk_collection, "add", this.RenderDesk);
		
	},

	/* Backbone event handling */
	events: {
		
	},

	/* Must have a render function */
	RenderCargo: function() {
		/* Get the template for this view (Prevents first load render) */
		var template = Cargo.Template.Get(this.options.template);
		
		/* Create a package of data for the render */
		var data_model = Cargo.API.GetDataPackage(this.options.dataset, this.cargo_collection.toJSON());

		/* Render the template and get the markup */
		this.Data.markup_cargo = Cargo.Core.Handlebars.Render(template, data_model);

		this.render();
	},

	/* Must have a render function */
	RenderDesk: function() {
		/* Get the template for this view (Prevents first load render) */
		var template = Cargo.Template.Get(this.options.template);

		/* Create a package of data for the render */
		var data_model = Cargo.API.GetDataPackage(this.options.dataset, this.desk_collection.toJSON());

		/* Render the template and get the markup */
		this.Data.markup_desk = Cargo.Core.Handlebars.Render(template, data_model);

		this.render();
	},

	render: function() {
		var remove_spinner = false;

		// if(this.Data.markup_desk == null) {
		// 	this.Data.markup_desk = "";
		// } else 
		if(this.Data.markup_cargo == null) {
			this.Data.markup_cargo = "";
		} else {
			remove_spinner = true;
		}

		// this.$el.html(this.Data.markup_cargo + this.Data.markup_desk);
		this.$el.html(this.Data.markup_cargo);

		if(remove_spinner) {
			$(".loading_animation", this.$el).remove();
		}

	}
});


/**
 * Backbone view for the form submit
 * This handles the case for both form submit types
 * The path to submit is in the HTML itself and this will send
 * the vars via POST methos
 */
Cargo.View.FormSubmit = Backbone.View.extend({
	
	initialize: function(options) {

	},

	/* Backbone event handling */
	events: {
		'submit' : 'SubmitForm'
	},

	/**
	 * Submit a form with data,
	 * but first validate it
	 * @param {Event} e Submit event
	 */
	SubmitForm: function(e) {
		e.preventDefault();

		if(this.ValidateForm()) {
			$('.submit_loader').show();
			$('input[type=submit]', this.$el).hide();

			$.ajax({
				url : this.$el.attr('action'), 
				dataType : "json",
				type: "POST",
				data : this.$el.serialize(),
				success : this.HandleReturn,
				error : function(e) {
					console.log("Error:", e);
				}
			});
		}
		
		return false;
	},

	/**
	 * Ensure all text inputs and textareas are 
	 * not blank. If they are, set an error class
	 * Return bool
	 */
	ValidateForm: function() {
		var valid = true; // optimistic

		$("input[type=text]",this.$el).each(function() {
			if($(this).val().trim() == "") {
				$(this).addClass('error');
				valid = false;
			} else {
				$(this).removeClass('error');
			}
		});

		$("textarea",this.$el).each(function() {
			if($(this).val().trim() == "") {
				$(this).addClass('error');
				valid = false;
			} else {
				$(this).removeClass('error');
			}
		});

		return valid;
	},

	/**
	 * Handle the form return value
	 * @param {JSON} data The data returned from the server
	 */
	HandleReturn: function(data) {
		if(data.error.length > 0) {
			alert(data.error);
		} else {
			if(data.jdata.public_url) {
				// document.location.href = data.jdata.public_url;
			
			// If no redirect url, show thanks
			} else {
				$(".thanks_message").show();
				$(".input_form").hide();
			}
		}

		$('.submit_loader').hide();
		$('input[type=submit]', this.$el).show();
	}
});

/**
 * Init and events
 */

$(function() {
	for (var key in Support) {
		if ( Support[key].setup !== undefined ) {
			Support[key].setup();
		}
	}
});

// When we know what design we're on
// Cargo.Event.on("support:loaded", function() {
// 	Support.DesignFilter.doFilter();
// });

// Project Load Complete
Cargo.Event.on("project_load_complete", function(pid) {
	// // If we've got a filter, go for it, otherwise wait till we do
	// if ( Support.Site.Data.filter ) {
	// 	Support.Site.setDesignFilter();
	// } else {
	// 	Cargo.Event.on("support:loaded", Support.Site.setDesignFilter);
	// }

	Support.Site.Project.LoadComplete();

});

