/**
 * @author Dale Larsen
 */
jQuery.fn.copyDimensions = function(elmToCopy){
	elmToCopy = $(elmToCopy);
	return $(this).width(elmToCopy.width()).height(elmToCopy.height());
};

jQuery.fn.vidPopup = function(){
	var $this = $(this);
	$this.click(function(e){
		e.preventDefault();
		var t_popupHtml = '';
		if ($this.attr('href')) {
			t_popupHtml = '<div style="margin-bottom: 40px; font-weight: bold; text-align: left;">' + $this.attr('title') + '</div><div><iframe width="560" height="345" src="http://www.youtube.com/embed/' + $this.attr('href') + '" frameborder="0" allowfullscreen></iframe></div>';
		} else {
			t_popupHtml = 'Coming Soon';
		}
		fullPopup.open(t_popupHtml, 600, 450, 'center', e, false, 500);
	});
}

jQuery.fn.dPanes = function(arg){
	var $this = $(this), opts = {}, initialized = false, $advancer = false;
	
	if (!arg || arg instanceof Object) {
		var defs = {
			paneClass: 'dPane',
			nextClass: 'dPaneNext',
			backClass: 'dPaneBack',
			onChange: false,
			onBeforeChange: false,
			onBack: false,
			onNext: false
		};
		opts = $.extend(defs, arg);
		$(this).data('dPane_opts', opts);
		
	} else {
		opts = $(this).data('dPane_opts');
		initialized = true;
	}
	
	var $allPanes = $this.find('.' + opts.paneClass);
	
	if (!initialized) {
		$allPanes.hide().eq(0).show();
	}
	
	function paneNext($nextPane){
		if ($nextPane.length) {
			$allPanes.hide();
			if (opts.onBeforeChange) opts.onBeforeChange.call(this, $nextPane);
			$nextPane.show();
			if (opts.onNext) opts.onNext.call(this, $nextPane);
			if (opts.onChange) opts.onChange.call(this, $nextPane);
		}
	}
	function paneBack($backPane){
		if ($backPane.length) {
			$allPanes.hide();
			if (opts.onBeforeChange) opts.onBeforeChange.call(this, $backPane);
			$backPane.show();
			if (opts.onBack) opts.onBack.call(this, $backPane);
			if (opts.onChange) opts.onChange.call(this, $backPane);
		}
	}
	
	if (!initialized) {
	
		$this.find('.' + opts.nextClass).click(function(){
			var $this1 = $(this);
			var $parentPane = $this1.closest('.' + opts.paneClass);
			var $nextPane = ($this1.attr('rel')) ? $parentPane.siblings($this1.attr('rel')) : $parentPane.next();
			paneNext($nextPane);
		});
		$this.find('.' + opts.backClass).click(function(){
			var $this1 = $(this);
			var $parentPane = $this1.closest('.' + opts.paneClass);
			var $backPane = ($this1.attr('rel')) ? $parentPane.siblings($this1.attr('rel')) : $parentPane.prev();
			paneBack($backPane)
		});
		
	}
	
	function paneChange($_showPane){
      if ($_showPane.length) {
         $allPanes.hide();
         if (opts.onBeforeChange) opts.onBeforeChange.call(this, $_showPane);
         $_showPane.show();
         if (opts.onChange) opts.onChange.call(this, $_showPane);
      }
	}
	
	$advancer = (typeof arg == 'number') ? $allPanes.eq(arg) : (typeof arg == 'string' ? (arg == 'next' ? $allPanes.eq($('.' + opts.paneClass + ':visible').index() + 1) : (arg == 'back' ? $allPanes.eq($('.' + opts.paneClass + ':visible').index() - 1) : $(arg))) : false);
	if ($advancer !== false) {
		paneChange($advancer);
	}
	
	return this;
};

jQuery.fn.hoursSelect = function(opts){
	var defs = {};
	opts = $.extend(defs, opts);
	var option_html = '';
	
	for (var i = 0; i < 24; i++) {
		option_html += '<option value="' + i + '">' + (i == 0 ? '12' : (i > 12 ? i - 12 : i)) + ':00 ' + (i < 12 ? 'am' : 'pm') + '</option>';
	};
	
	return this.each(function(){
		$(this).html(option_html);
	});
	
};

function cb_to_obj(_s){ //typically this is a name assigned to the checkboxes. However, you can use classes too. Ids are not allowed (ids should be unique)
	if (_s.match(/\#/)) throw 'Ids are not allowed in the selector for function cb_to_obj';
	if (!_s.match(/\./)) _s = '[name="' + _s + '"]'; //assume we are passing in a name
	var $items = $(_s), retObj = {};
	$items.each(function(i){
		var $this = $(this);
		retObj[i] = {
			id: $this.attr('id'),
			value: $this.val(),
			checked: $this.attr('checked')
		}
	});
	return retObj;
}

jQuery.fn.textToInput = function(opts){

	var defs = {
		trigger: false,
		showCallback: false,
		hideCallback: false,
		triggerVisibleTxt: '',
		triggerHiddenTxt: '',
		validationRegex: false,
		errorCont: false,
		errorMsg: 'Invalid input.'
	};
	
	var opts = $.extend(defs, opts);
	
	var $this = $(this), $trigger = false;
	
	if (opts.trigger === false) {
		throw 'opts.trigger is undefined on the "textToInput" jquery method.';
		return $this;
	} else {
		$trigger = $(opts.trigger);
	}
	
	var $errorCont = (opts.errorCont) ? $(opts.errorCont) : false;
	
	$trigger.text(opts.triggerHiddenTxt).click(function(){
		if ($errorCont) $errorCont.hide();
		var this_text = $this.text(), this_width = $this.width() + 10;
		var $thisInput = $('#' + $this.attr('id') + '_input');
		
		if ($thisInput.length && $thisInput.is(':visible')) {
		
			function _allowShow(){
				$thisInput.hide();
				$this.text($thisInput.val()).show();
				$trigger.text(opts.triggerHiddenTxt)
				if (opts.hideCallback) opts.hideCallback.call(this, $thisInput.val());
			}
			
			if (opts.validationRegex !== false && opts.validationRegex instanceof RegExp) {
			
				if ($thisInput.val().match(opts.validationRegex)) {
					if ($errorCont) $errorCont.html(opts.errorMsg).show();
					
					return false;
				} else {
					_allowShow();
				}
			} else {
				_allowShow();
			}
			
		} else if ($thisInput.length && !$thisInput.is(':visible')) {
		
		
			$this.hide();
			$thisInput.val(this_text).width(this_width).show();
			$trigger.text(opts.triggerVisibleTxt);
			if (opts.showCallback) opts.showCallback.call(this);
		} else {
		
			$thisInput = $('<input id="' + $this.attr('id') + '_input" type="text" style="display: inline;" />').hide().insertAfter($this).val(this_text).width(this_width);
			
			$this.hide();
			$thisInput.show();
			$trigger.text(opts.triggerVisibleTxt);
			
			$thisInput.keydown(function(){
				$this.text($thisInput.val());
				$thisInput.width($this.width() + 10);
			});
			
			if (opts.showCallback) opts.showCallback.call(this);
		}
		
	});
	
	return $this;
}

/***
 * This is probably not the best place for this but its here til I define a better one.
 */
jQuery.fn.tlpProgressBar = function(opts){

	var defs = {
		pathInfo: false,
		fillWidth: 695
	};
	
	opts = $.extend(defs, opts);
	/** TLP Lite (Foundations)
	 * Segment 1: Files 001-010 - FS
	 * Segment 2: Files 011-050 - SI
	 * Segment 3: Files 051-080 - SL
	 * Segment 4: Files 081-140 - HS
	 * Segment 5: Files 141-170 - SL
	 * Segment 6: Files 171-190 - SI
	 * Segment 7: Files 191-200 - FS
	 */
	var pathRanges = {
		1: {//this property represents a pathId, 1 is TLP Lite (foundations)
			1: {//segment 1
				name: 'Full Spectrum',
				type: 'fs',
				start: 1,
				end: 10,
				color: '#07bcd0'
			},
			2: {
				name: 'Foundational / Sensory',
				type: 'si',
				start: 11,
				end: 50,
				color: '#c1d83c'
			},
			3: {
				name: 'Cognitive / Communication',
				type: 'sl',
				start: 51,
				end: 80,
				color: '#fdaa26'
			},
			4: {
				name: 'Creative / Alertness',
				type: 'hs',
				start: 81,
				end: 140,
				color: '#fb3f41'
			},
			5: {
				name: 'Cognitive / Communication',
				type: 'sl',
				start: 141,
				end: 170,
				color: '#fdaa26'
			},
			6: {
				name: 'Foundational / Sensory',
				type: 'si',
				start: 171,
				end: 190,
				color: '#c1d83c'
			},
			7: {
				name: 'Full Spectrum',
				type: 'fs',
				start: 191,
				end: 200,
				color: '#07bcd0'
			}
		}
	}
	
	return this.each(function(){
		if (opts.pathInfo && opts.pathInfo.hasOwnProperty('lastStepCompleted')) {
			var pathInfo = opts.pathInfo;
			
			var $this = $(this).addClass('tlpProgressBar').width('auto');
			
			var $fillBar = $('<div class="tlpProgressBar_fill"></div>').appendTo($this);
			
			var lastStepCompleted = pathInfo.lastStepCompleted;
			
			var d_pathRange = pathRanges[pathInfo.pathId], d_range = {}, next_range = {}, lastRangeStep = 0, nextRangeBefore = false;
			
			for (x in d_pathRange) {
				if ((lastStepCompleted >= d_pathRange[x].start && lastStepCompleted <= d_pathRange[x].end) || (lastStepCompleted == 0 && d_pathRange[x].start == 1)) {
					var lastStepIsLast = lastStepCompleted === d_pathRange[x].end;
					d_range = (lastStepIsLast) ? d_pathRange[parseInt(x) + 1] : d_pathRange[x];
					next_range = d_pathRange[parseInt(x) + (lastStepIsLast ? 2 : 1)];
					lastRangeStep = lastStepCompleted - d_range.start + 1;
					if (!next_range) {
						next_range = d_pathRange[parseInt(x) - 1];
						nextRangeBefore = true;
					}
				}
			}
			
			$fillBar.css({
				'border': '1px solid ' + d_range.color
			});
			
			var $fillBarSep = $('<div class="tlpProgressBar_fill_sep"></div>');
			
			var $nextFillBar = $('<div class="tlpProgressBar_fill_next"></div>').css({
				'border': '1px solid ' + next_range.color
			});
			
			if (nextRangeBefore) {
				$nextFillBar.insertBefore($fillBar);
				$fillBarSep.insertBefore($fillBar);
			} else {
				$fillBarSep.appendTo($this);
				$nextFillBar.appendTo($this);
				$this.css('borderRight', '0px solid #fff');
			}
			
			var $fillBarSepArrow = $('<div class="tlpProgressBar_fill_sep_arrow"></div>').appendTo($fillBarSep);
			
			var segmentLength = d_range.end - d_range.start + 1;
			var nextSegmentLength = (next_range) ? next_range.end - next_range.start + 1 : 0;
			var allSegmentLength = segmentLength + nextSegmentLength;
			var fillersWidth = (parseInt(opts.fillWidth / allSegmentLength) - 1);
			
			for (var i = 0; i < segmentLength; i++) {
			
				$('<div class="tlpProgressBar_fillers"></div>').css({
					backgroundColor: (i <= lastRangeStep - 1 ? d_range.color : '#fff'),
					borderRight: (i == (segmentLength - 1) ? '' : '1px solid ' + d_range.color),
					width: fillersWidth + 'px'
				}).appendTo($fillBar);
				
			}
			
			var $tlpProgressBar_arrow = $('<div class="tlpProgressBar_arrow"></div>').css('left', ((lastRangeStep * (fillersWidth + 1) + 1) - 8) + 'px').appendTo($fillBar);
			var $tlpProgressBar_percent = $('<div class="tlpProgressBar_percent"></div>').appendTo($tlpProgressBar_arrow).html(parseInt((lastRangeStep / segmentLength) * 100) + '%');
			var $cycleTitle = $('<div class="tlpProgressBar_cycleTitle">' + d_range.name + '</div>').appendTo($fillBar);
			
			for (var i = 0; i < nextSegmentLength; i++) {
				$('<div class="tlpProgressBar_fillers"></div>').css({
					backgroundColor: next_range.color,
					borderRight: (i == (nextSegmentLength - 1) ? '' : '1px solid ' + next_range.color),
					width: fillersWidth + 'px'
				}).appendTo($nextFillBar);
			}
			var $nextCycleTitle = $('<div class="tlpProgressBar_nextCycleTitle">' + next_range.name + '</div>').appendTo($nextFillBar);
			
		} else {
			$(this).html('Progress will be tracked once your sessions become available.')
		}
		
	});
}

function detectCycleFromFile(url){
	return url.match(/\_fs\_|\_si\_|\_sl\_|\_hs\_/)[0];
}

jQuery.fn.tabLink = function($tabObj){//we assume $tabObjis a jquery objet with tabs assigned
	return this.each(function(){
	
		var $this = $(this).click(function(){
			$tabObj.tabs('select', $this.attr('href'));
		});
		
	});
	
}

/*
 //Get
 {
 0: {
 table: 'table1',
 tableid: 1,
 column: 'test'
 }
 }
 //SET
 {
 0: {
 table: 'table1',
 tableid: 1,
 column: 'test',
 value: false
 },
 1: {
 table: 'table2',
 tableid: 4,
 column: 'test6',
 value: 'something here'
 }
 }
 */
var db = {
	get: function(postObj, callback){
		var retObj = {};
		$.ajax({
			type: 'post',
			url: '/setget/get.do',
			data: postObj,
			success: function(data){
				retObj = data;
				if (callback) callback.call(this, retObj);
			},
			async: false
		});
		return retObj;
	},
	set: function(postObj, callback){
		$.post('/setget/set.do', postObj, callback);
	}
}

jQuery.fn.inlinePopup = function(){

	return this.each(function(){
	
		var $this = $(this);
		
		$this.click(function(){
			var contents = $this.attr('href'), w = parseInt($this.attr('w')), h = parseInt($this.attr('h'));
			
			function launchPopup(popupHtml){
				fullPopup.open(popupHtml, w, h, 'center');
			}
			
			if (contents.match(/^#/)) {//if the first character is a #, then look for the contents in an element on the page
				launchPopup($(contents).html());
			} else {
				$.get(contents, function(popupHtml){
					launchPopup(popupHtml);
				});
			}
		});
	});
	
};

