// we'll need this later in case our first widget dies
var backupListings = $('#' + this.domId + '_listing').clone();

// global scope for calling methods later
var widgetInstance 

// this is where we store whether or not we tried refreshing the widget
// when displayAndExit event was triggered
var max_refreshes = 2;
var refresh_count = 0;

// this is where we take default rollup params and use them to refresh
// a new widget instance
function refreshWidgets(){

	$('.cachedWidget').each(function(){    	

		var widget = $(this); // get the DOM element we're updating
		
		widget.hide(); // first hide it

		widgetInstance = new QS.WidgetInstance();
		
		if(refresh_count <= max_refreshes)
		{
			refresh_count++;
			
			try
			{

				id = widget.attr('id');
				split_id = id.split('_');
				domId = split_id[0]; // get the dom id

				// remove the old parameters
				$("#" + domId + "_filterCriteria").remove();
				$("#" + domId + "_dataValues").remove();

				// rename the default parameters
				$("#defaultRollup_filterCriteria").attr('id', domId + "_filterCriteria");
				$("#defaultRollup_dataValues").attr('id', domId + "_dataValues");
				
				widgetInstance.construct(widget);

				// this calls xapi for updated listings, populates
				// the objects and renders the updated widget
				widgetInstance.updateWidget();
			}
			catch (e)
			{
				widgetInstance.construct(widget);
				// we're not too concerned with the error here,
				// we'll just show the on-page widget
				widgetInstance.restoreOnPageWidgetAndExit();
			}
		}
		else
		{
			widgetInstance.restoreOnPageWidgetAndExit();
		}
		
	}); // end $('.cachedWidget').each()

};

// Some helper functions for making links
QS.UrlHelper = Backbone.Model.extend({
	construct: function(){
		this.hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	},
	getBuildString: function() {
		return this.hashes.join('&');
	},
	getUrlVars: function(){
		var vars = [], hash;
		var hash = this.hashes;
		for(var i = 0; i < hashes.length; i++)
		{
		  hash = hashes[i].split('=');
		  vars.push(hash[0]);
		  vars[hash[0]] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
});

// recreate the show all programs effect using custom animate
// attributes since new jQuery version breaks the existing
// animation
QsWidgetEvents = function(event, obj)
{
	switch (event)
	{	
	    case "QS.WidgetInstance:render:out":
			$(".programs h3").click(function(){
				
				$(this).next("ul").animate({height: "toggle"}, 600)
					.siblings("ul:visible").slideUp(600);
				$(this).toggleClass("active");
				$(this).siblings("h3").removeClass("active");
			});
			$("#collapse_all_message").click(function(){
				$(".programs ul").animate({height: "hide"}, 600);
				$(".programs ul").siblings("h3").removeClass("active");
				return false; 
			});
			$("#show_all_message").click(function(){
				$(".programs ul").animate({height: "show"}, 600);
				$(".programs ul").siblings("h3").addClass("active");
				return false; 
			});
			if("1"==getParamValue("prog")) {
				$(".programs ul").slideDown();
				$(".programs ul").siblings("h3").addClass("active");
			}			
			break;
	}
}

var has_qs_widget = typeof QS.WidgetInstance != 'undefined';
var has_qs_vendor = typeof QS.Vendor != 'undefined';
var has_qs_dealer = typeof QS.Dealer != 'undefined';
var has_qs_progressbar = typeof QS.ProgressBarLoadEffect != 'undefined';

//we are tweaking the spinner here so that it doesn't appear
//mulitple times on the page when doing rollup widget refresh
if (has_qs_progressbar){
	QS.ProgressBarLoadEffect = QS.ProgressBarLoadEffect.extend({
			
		listener            : function(event, obj)
		{
			switch (event)
			{
				case "QS.WidgetInstance:updateWidget:in":	
					$('.sblLoadingDiv').remove();	
					$("#bottom div#search").hide();
					$("#footer").addClass("bottomfooter");					
					this.startEffect();		
					break;
            	case "QS.WidgetInstance:populate:in":					
	            case "QS.WidgetInstance:updateWidget:preAjax":
	                this.updateProgressBar();
	                break;          
	            case "QS.WidgetInstance:displayAndExit:in":
	            case "QS.WidgetInstance:display:in":	                
	            case "QS.WidgetInstance:render:in":
	                this.completeProgressBar(); 
					$("#bottom div#search").show();
					$("#footer").removeClass("bottomfooter");
	                break;
	            case "QS.WidgetInstance:restoreOnPageWidgetAndExit:in":	                
	            case "QS.WidgetInstance:qsit:out":
	                this.completeProgressBar(true);
					$("#bottom div#search").show();
					$("#footer").removeClass("bottomfooter");
	                break; 	
			}
		}
	});
}

// check if xapi is loaded and increase timeout limit
// also extend display method to only show listings when school
// count is greater than zero. otherwise, use the rollup params
if (has_qs_widget)
{
	QS.WidgetInstance = QS.WidgetInstance.extend({
		sv_xapiTimeout: 15000,
		display                 :   function()
		{
			// show the dom element and fire off impression tracking
			this.trigger('QS.WidgetInstance:display:in', this);
			if(this.totalResults > 0)
			{
				this.domElement.show();
				this.qsit();
				this.removeCtHandlers('.qsctCached'); // remove these click handlers
				this.setCtHandlers('.qsct'); // adds click handlers to the updated widget
				this.setCtHandlers('.qsctSite');
			}
			else
			{
				refreshWidgets();
			}
			this.trigger('QS.WidgetInstance:display:out', this);
		},
	    restoreOnPageWidgetAndExit  :   function(request, status, error)
		{
			this.trigger('QS.WidgetInstance:restoreOnPageWidgetAndExit:in', this);
			this.removeUpdatedWidgetListing();		
			backupListings.appendTo(this.domElement);
			this.setCtHandlers('.qsctCached'); // restore click handlers
			// show the dom element and fire off impression tracking
			this.domElement.show();
			this.qsit();
			this.trigger('QS.WidgetInstance:restoreOnPageWidgetAndExit:out', this);
			return;
	    }
	});
}


//add a method to check for leading slash in logopath
//also grab dealer key
if (has_qs_vendor)
{
	QS.Vendor = QS.Vendor.extend({
		doLeadingSlashLogoPath		: function(){
			if(this.data.logoPath.indexOf('/') != 0) this.data.logoPath = '/' + this.data.logoPath;
			return this.data.logoPath;
		},
		getLogoPathLength			: function(){
			return this.data.logoPath.length;
		},
		getDealerKey				: function(numIndex){
			var self = (this.data) ? this.data : this;
			if (self.dealers.length > 0 && numIndex <= self.dealers.length)
			{
				return self.dealers[numIndex].getDealerKey();
			}
		}
	});
}

// Change "Online School" to say "Online" only
if (has_qs_dealer)
{
	QS.Dealer = QS.Dealer.extend({
		getDealerType			: function(){
			if(this.campusType == 'Online School') return 'Online';
			else return this.campusType;
		}
	});
}
