// $Id: quicktabs.js,v 1.3.2.16 2009/03/16 20:35:31 katbailey Exp $
var pagers = new Array ( ) ;

$(function (){
	$(".pagerLink").each (function(intIndex){
		if ( typeof ( this.firstChild ) != "undefined" &&
			this.firstChild.nodeName.toLowerCase()  == "a" ) {
			pagers[intIndex] = this.firstChild.search ;
			//alert ( this.firstChild.search ) ;
			if ( this.firstChild.search != "" ) {
				$(this).attr ( "id", "start" + intIndex.toString()) ;
				$(this).context.id=intIndex.toString() ;
				alert ( $ ( this ).html ( ) ) ;
				$(this).attr ( "style", "cursor:pointer;" );
				$(this).bind ( "click", function(obj){
					/*if ( typeof ( pagers[obj.target.id] )!="undefined"){
						//alert ( pagers [ obj.target.id ] ) ;
						//quicktabsClick ( ) ;
						//var tab = new Drupal.quicktabs.tab(this);
						// alert ( $(".active").target.id );
						$(this).parents('li').siblings().removeClass('active');
						$(this).parents('li').addClass('active');
						tab.container.children().hide();
						if (tab.tabpage.hasClass('quicktabs_tabpage')) {
							tab.tabpage.show();
						} else {
							if ($(this).hasClass('qt_ajax_tab')) {
								tab.startProgress();
								if (tab.tabObj.type != 'view') {
									var qtAjaxPath = Drupal.settings.basePath + 'quicktabs/ajax/' + tab.tabObj.type + '/';
									switch (tab.tabObj.type) {
										case 'node':
											qtAjaxPath += tab.tabObj.nid + '/' + tab.tabObj.teaser + '/' + tab.tabObj.hide_title;
										break;
										case 'block':
											qtAjaxPath += tab.tabObj.bid + '/' + tab.tabObj.hide_title;
										break;
										case 'qtabs':
											qtAjaxPath += tab.tabObj.qtid;
										break;
									}
									$.ajax({
										url: qtAjaxPath,
										type: 'GET',
										data: null,
										success: tab.options.success,
										complete: tab.options.complete,
										dataType: 'json'
									});
								} else {
									tab.quicktabsAjaxView();
								}
							}
						}
						return false;
					}*/
				});
				$(this).html(this.firstChild.innerHTML);
			}
		}
	});			
});

function attachBehaviors(context) {
	$.each(Drupal.settings.views_accordion, function(id) {
		var activeClass = 'accordion-header-active';
		// the CSS class that the active header will recieve when it's open
		var hoverClass = 'accordion-header-hover';
		// the CSS class that the headers will recieve when the mouse goes over
		var contentClass = 'accordion-content';
		// the CSS class that the content in the accordions will have
		var usegroupheader = this.usegroupheader;
		var grouped = this.grouping;
		// wether or not field grouping is enabled
		var keeponeopen = this.keeponeopen;
		// wether or not we'll be allowing the user to close opened items
		var startallopen = this.startallopen;
		var speed = this.speed;  // how fast the sliding will be
		var firstopen = this.firstopen;  // wether or not the first item will start opened
		var cycleOn = this.autocycle; // wether or not we'll be using auto cycling of items
		var cycleSpeed = this.autocyclespeed;
		// time between each cycle (added to speed below to avoid weird behaviour)
		var togglelinks = this.togglelinks;  // wether or not to show Open All / Close All links
		// the selectors we have to play with
		var contentSelector = 'div.' + contentClass;
		// used for selecting all accordion content to show/hide
		var displaySelector = this.display;
		// already comes with div. in front. Used to grab anything under our view.
		var headerSelector = usegroupheader ? (this.header) : ('.' + this.header);
		// this.header is the class of our first field
		// we have to use different selectors if using field 
		// grouping because we have several divs with #id
		var idSelector = grouped ? ('.' + id) : ('#' + id);
		var $viewcontent = usegroupheader ? $(displaySelector + ' div.view-content').parent() : $(displaySelector + ' div.view-content');
		
		var hasRan = $(idSelector + ' ' + contentSelector).length;
		var $triggers = usegroupheader ? $(displaySelector + ' ' + headerSelector) : $(idSelector + ' ' + headerSelector);
		$triggers.addClass('accordion-header');

		$triggers.parent().each(function(){
			$(this).children().slice(1).wrapAll('<div class="' + contentClass + '">')
			// we wrap all but the header in a div so we can target the content later
		}).parent().addClass('accordion-active');
		var $content =  usegroupheader ? $(contentSelector) : $(idSelector + ' ' + contentSelector);

		$content.hide(); 
		if ( startallopen ){
			$content.show();
		}
		// Hide all - show all action & buttons
		if (!cycleOn && togglelinks) {
			$viewcontent.prepend('<span class="toggleAccordion"><a class="open-all-accordion" href="#">' + Drupal.t('Open All') + '</a> | <a class="close-all-accordion" href="#">' + Drupal.t('Close All') + '</a></span>');
			$(displaySelector + ' span.toggleAccordion a.close-all-accordion').click(function(){
				$content.hide();
				$triggers.removeClass(activeClass);
				return false;
			});
			$(displaySelector + ' span.toggleAccordion a.open-all-accordion').click(function(){
				$content.show();
				$triggers.addClass(activeClass);
				return false;
			});
		}
		/*
		*  Accordion action
		*/ 
		$triggers.click(function(ev) {
			if (ev.detail === 1 || !ev.detail) {
				// so we prevent double clicking madness (for not so savy web users)
				// !ev.detail is for when its triggered by code
				// so we keep accordions for each field group are independent (if using field groups)
				var $contentToHandle = (grouped && (!usegroupheader)) ?
					$(this).parents(idSelector).children().children().children(contentSelector) :
					$content;
				var $ourTrigger = $(this);
				var $ourContent = $(this).next();
				var $ourContentVisible = $ourContent.is(":visible");

				// if the one we clicked is open
				if ($ourContentVisible) {
					if(keeponeopen === 0) {
						$ourContent.slideUp(speed);
						$(this).removeClass(activeClass);
					}
				}
				// otherwise
				else if (!$ourContentVisible) {
					// if we have one open, close it
					var $visibleContent = $contentToHandle.filter(':visible');
					if($visibleContent.length) {
						$triggers.removeClass(activeClass);
						$visibleContent.slideUp(speed);
					}
					// and open our section
					$ourContent.slideToggle(speed);
					$(this).addClass(activeClass);
					}
				}
				return false;
			});
	
			$triggers.hover(function(){
				// on mouse over
				$(this).addClass(hoverClass);
			},function(){
				// on mouse out
				$(this).removeClass(hoverClass);
			});
	
			// show the first item if so configured
			if (firstopen) {
				$triggers.filter(':first').addClass(activeClass).next().show();
			}
	
			/*
			* Auto-Cycling through the accordion
			*/ 
			if (cycleOn) {
				var running = true;
				var interval = speed + cycleSpeed;  // (animation time + cycle time)
				var hardstop = false;
				// creating buttons stop/start/ paused status
				$viewcontent.prepend('<span class="stop-accordion"><a class="stop-accordion" href="#">' + Drupal.t('Stop') + '</a></span>');
				var $stoplink = $(displaySelector + ' span.stop-accordion a.stop-accordion');
	
				// main cycle action
				function cycleAccordion() {
					if (running) {
						var $activeHeader = $triggers.filter('.' + activeClass);
						var $firstHeader = $triggers.filter(':first');
						var $nextHeader = $activeHeader.parent().next().children().filter(':first');
						var $triggerToClick = ($nextHeader.length) ? $nextHeader : $firstHeader;
						$triggerToClick.trigger("click");
					}
					setTimeout(cycleAccordion, interval);
				}
				setTimeout(cycleAccordion, interval);
				/*
				* BUTTONS to stop/start cycling action
				*/
				$stoplink.click(function() {
				if (hardstop === true) {
					$triggers.filter(':first').trigger('start');
					$(this).html(Drupal.t('Stop'));
				}else if (hardstop === false) {
					$triggers.filter(':first').trigger('stop');
					$(this).html(Drupal.t('Start'));
				}
				hardstop = (hardstop === true) ? false : true;
				return false;
			});
			/*
			* Stop cycling on mouse over the whole thing
			*/
			$triggers.parent().parent().hover(function () {
				// on mouse over
				if (!hardstop) {
					$triggers.filter(':first').trigger('stop');
					$stoplink.html(Drupal.t('Paused'));
				}
			}, function () {
				// on mouse out
				if (!hardstop){
					$triggers.filter(':first').trigger('start');
					$stoplink.html(Drupal.t('Stop'));
				}
			});
			$triggers.bind('stop', function () {
				running = false;
			}).bind('start', function () {
				running = true;
			});
		} // end autocycle
	});
};

function QuickTabsView ( target, response ) {
	if (response.debug) {
		alert(response.debug);
	}
	var $view = $(target);
	var $first = true ;
	var $sfirst = true ;
	var startallopen = 0 ;
	if ( typeof ( Drupal.settings.views_accordion ) != "undefined" &&
				 typeof ( Drupal.settings.views_accordion['views-accordion-testimonials_view-default'] ) != "undefined" ){  
		startallopen =Drupal.settings.views_accordion['views-accordion-testimonials_view-default'].startallopen;
	}
	if (response.status && response.display) {
		var $newView = $(response.display);
		$view.replaceWith($newView);
		$view = $newView;
		$('.views-accordion-item').each(function(){
			var viewtitle = $(this).children('.views-field-title');
			var viewbody = $(this).children(".views-field-body");
			$(this).parent().parent().addClass('accordion-active');
			$(this).children ( ".views-field-body" ).remove ( ) ;
			if ( viewbody.html() != null ) {
				if ( startallopen){
						viewtitle.addClass ( "accordion-header" ) ;
						viewtitle.addClass('accordion-header-active').next().show();
						var html = viewbody.html() ;
						$(this).append ( "<div style='display:block;clear:both;' class='accordion-content'><div  class='views-field-body'>" + viewbody.html() + "</div></div>" ) ;
						$sfirst = false ;
				}else{
					if ( $sfirst ) {
						viewtitle.addClass ( "accordion-header" ) ;
						viewtitle.addClass('accordion-header-active').next().show();
						var html = viewbody.html() ;
						$(this).append ( "<div style='display:block;clear:both' class='accordion-content'><div class='views-field-body'>" + viewbody.html() + "</div></div>" ) ;
						$sfirst = false ;
					}else{
						viewtitle.addClass ( "accordion-header" ) ;
						var html = viewbody.html() ;
						$(this).append ( "<div style='display:none' class='accordion-content'><div class='views-field-body'>" + viewbody.html() + "</div></div>" ) ;
					}
				}
				viewtitle.click(function(ev) {
					var speed = 200 ;
					if (ev.detail === 1 || !ev.detail) {
						var $contentToHandle = $('.accordion-content');
						var $ourTrigger = $(this);
						var $ourContent = $(this).next();
						var $ourContentVisible = $ourContent.is(":visible");
						if ($ourContentVisible) {
							$ourContent.slideUp(speed);
							$(this).removeClass('accordion-header-active');
						} else if (!$ourContentVisible) {
							var $visibleContent = $contentToHandle.filter(':visible');
							if($visibleContent.length) {
								$visibleContent.prev().removeClass('accordion-header-active');
								$visibleContent.slideUp(speed);
							}
							$ourContent.slideToggle(speed);
							$(this).addClass('accordion-header-active');
						}
					}
					return false;
				});
			}
		});
	}
	if (response.messages) {
		// Show any messages (but first remove old ones, if there are any).
		$view.find('.views-messages').remove().end().prepend(response.messages);
	}
}

function print_r(theObj){
	var output = "" ;
	if(theObj.constructor == Array ||
		theObj.constructor == Object){
		for(var p in theObj){
			if(theObj[p].constructor == Array||
				theObj[p].constructor == Object){
				output += "["+p+"] => "+typeof(theObj)+"\n";
				output += print_r(theObj[p]);
			} else {
				output += "["+p+"] => "+theObj[p]+"\n";
			}
		}
	}
	return output ;
}

Drupal.settings.views = Drupal.settings.views || {'ajax_path': 'views/ajax'};

Drupal.behaviors.quicktabs = function (context) {
	$('.quicktabs_wrapper:not(.quicktabs-processed)', context)
		.addClass('quicktabs-processed').each(function(){
		Drupal.quicktabs.prepare(this);
	});
};

Drupal.quicktabs = Drupal.quicktabs || {};

// setting up the inital behaviours
Drupal.quicktabs.prepare = function(el) {
	var i = 0;
	var qtid = el.id.split('-')[1];
	$(el).find('ul.quicktabs_tabs li a').each(function(){
		this.myTabIndex = i++;
		this.qtid = qtid;
		$(this).bind('click', quicktabsClick);
	});

	// Search for the active tab.
	var $active_tab = $(el).children('.quicktabs_tabs').find('li.active a');
	if ($active_tab.hasClass('qt_tab') || $active_tab.hasClass('qt_ajax_tab')) {
		$active_tab.trigger('click');
	} else {
		//Click on the first tab.
		//$(el).children('.quicktabs_tabs').find('li.first a').trigger('click');
	}
	return false;
}

// constructor for an individual tab
Drupal.quicktabs.tab = function (el) {
	this.element = el;
	this.tabIndex = el.myTabIndex;
	this.qtid = el.qtid;
	var qtKey = 'qt_' + this.qtid;
	var i = 0;
	for (var key in Drupal.settings.quicktabs[qtKey].tabs) {
		if (i == this.tabIndex) {
			this.tabObj = Drupal.settings.quicktabs[qtKey].tabs[key];
			this.tabKey = key;
		}
		i++;
	}
	this.tabpage_id = 'quicktabs_tabpage_' + this.qtid + '_' + this.tabKey;
	this.container = $('#quicktabs_container_' + this.qtid);
	this.tabpage = this.container.find('#' + this.tabpage_id);
	// The 'this' variable will not persist inside of the options object.
	var tab = this;
	this.options = {
		success: function(response) {
			return tab.success(response);
		},
		complete: function(response) {
			return tab.complete();
		}
	}
}

// ajax callback for non-views tabs
Drupal.quicktabs.tab.prototype.success = function(response) {
	var result = Drupal.parseJson(response.data);
	this.container.append(Drupal.theme('quicktabsResponse', this, result));
	Drupal.attachBehaviors(this.container);
}

// function to call on completed ajax call
// for non-views tabs
Drupal.quicktabs.tab.prototype.complete = function() {
	// stop the progress bar
	this.stopProgress();
}

Drupal.quicktabs.tab.prototype.stopProgress = function(){
   	$(".pagerLink").each (function(intIndex){
		$(this)[0].id="" + intIndex ;
		if ( $(this)[0].firstChild != null ){
			pagers[intIndex] = $(this)[0].firstChild.search ;
			$(this).html($(this)[0].firstChild.innerHTML);
			$(this).bind ( "click", function(obj){
				if ( typeof ( pagers[obj.id] )!="undefined"){
					alert ( pagers[obj.id]) ;
				}
			});
		}
	});			
	if (this.progress.element) {
		$(this.progress.element).remove();
	}
	$(this.element).removeClass('progress-disabled').attr('disabled', false);
}

Drupal.quicktabs.tab.prototype.startProgress = function () {
	var progressBar = new Drupal.progressBar('qt-progress-' + this.element.id, null, null, null);
	progressBar.setProgress(-1, Drupal.t('Loading'));
	this.progress = {};
	this.progress.element = $(progressBar.element).addClass('qt-progress qt-progress-bar');
	this.container.prepend(this.progress.element);
}

Drupal.quicktabs.tab.prototype.quicktabsAjaxView = function() {
	// Create an empty div for the tabpage. The generated view will be inserted into this.
	var tab = this;
	tab.container.append(Drupal.theme('quicktabsResponse', this, null));
	var target;
	target = $('#' + tab.tabpage_id + ' > div');
	var ajax_path = Drupal.settings.views.ajax_path;
	//If there are multiple views this might've ended up showing up multiple times.
	if (ajax_path.constructor.toString().indexOf("Array") != -1) {
		if  ( window.location.search == '' ) {
			ajax_path = ajax_path[0] + "?active_item=0"  ;
		}else{
			ajax_path = ajax_path[0] + window.location.search + "active_item=0"  ;
		}
	}
	var args;
	if (tab.tabObj.args != '') {
		args = tab.tabObj.args.join('/');
	} else {
		args = '';
	}
	path = window.location.pathname.substr ( 1 ) ;
	var viewData = {
		'view_name': tab.tabObj.vid,
		'view_display_id': tab.tabObj.display,
		'view_args': args,
		'view_path':  path
	}
	$.ajax({
		url: ajax_path,
		type: 'GET',
		data: viewData,
		success: function(response) {
			// Call all callbacks.
			if (response.__callbacks) {
				$.each(response.__callbacks, function(i, callback) {
					eval('QuickTabsView')(target, response);
				});
			}
		},
		complete: function() {
			tab.stopProgress();
		},
		error: function() { alert(Drupal.t("An error occurred at @path.", {'@path': ajax_path})); },
		dataType: 'json'
	});
}

var quicktabsClick = function() {
	var tab = new Drupal.quicktabs.tab(this);
	// Set clicked tab to active.
	$(this).parents('li').siblings().removeClass('active');
	$(this).parents('li').addClass('active');
	// Hide all tabpages.
	tab.container.children().hide();
	// Show the active tabpage.
	/*if (tab.tabpage.hasClass('quicktabs_tabpage')){
		tab.tabpage.show();
	}else{*/
		if ($(this).hasClass('qt_ajax_tab')) {
			tab.startProgress();
			// Construct the ajax tabpage.
			if (tab.tabObj.type != 'view') {
			// construct the ajax path to retrieve the content, depending on type
				var qtAjaxPath = Drupal.settings.basePath + 'quicktabs/ajax/' + tab.tabObj.type + '/';
				switch (tab.tabObj.type) {
					case 'node':
						qtAjaxPath +=  tab.tabObj.nid + '/' + tab.tabObj.teaser + '/' + tab.tabObj.hide_title;
					break;
					case 'block':
						qtAjaxPath +=  tab.tabObj.bid + '/' + tab.tabObj.hide_title;
					break;
					case 'qtabs':
						qtAjaxPath +=  tab.tabObj.qtid;
					break;
				}
				$.ajax({
					url: qtAjaxPath,
					type: 'GET',
					data: null,
					success: tab.options.success,
					complete: tab.options.complete,
					dataType: 'json'
				});
			} else {
				// special treatment for views
				tab.quicktabsAjaxView();
			}
		}
	//}
	return false;
}
// theme function for ajax response
Drupal.theme.prototype.quicktabsResponse = function(tab, result) {
	var newDiv = tab.tabObj.type == 'view' ? '<div id="' + tab.tabpage_id + '" class="quicktabs_tabpage"><div></div></div>' : '<div id="' + tab.tabpage_id + '" class="quicktabs_tabpage">' + result['data'] + '</div>';
	return newDiv;
};