// this is for my portfolio
(function($) {
	var undefined;
	if (window.wtd == undefined) window.wtd = {};
	if (window.console == undefined) {
		window.console = {
			log: function(msg) {
				//alert(msg);
			}
		}
	}

	var headerId = "masthead",
		$wrapper = $('#wrapper'),
		$content = $('#content'),
		$header = $('#' + headerId),
		$nav = $('#projects-nav'),
		$projects = $('#projects-wrap'),
		$submit = $('#submit'),
		$win = $(window),
		staticLeft = 0;
		
	wtd = {
		helpers: Helpers(),
		fns: {
			slider: Slider(),
			toggleScroll: function(arg) { ToggleScrollLink(arg); }
		}
	};
	
	function Helpers () {
		var self = this;
		
		self.return_random_quad = function() {
			var m = Math.round(Math.random()*100);
			return m > 75 ? 4 : m <= 75 && m > 50 ? 3 : m <= 50 && m > 25 ? 2 : 1;
		}
		
		self.check_property = function(obj, p) {
			if (obj.hasOwnProperty(p) && obj[p]) {
				return true;
			}
			return false;
		}
		
		self.supports_style = function (prop) {
			// console.log($('.project-tab a span').css(prop));
		};
		
		self.stringify_simple_object = function(obj, joiner) {
			var s = [], j = joiner || ',';
			for (var p in obj) {
				if (self.check_property(obj, p)) {
					s.push(p + ':' + obj[p]);
				}
			}
			return s.join(j);
		};
		self.toggle_classes = function (sEl, aosKlass, sToggle, sType) {
		/*
			@sEl:	STRING, selector
			@aosKlass:	STRING/OBJECT/ARRAY of classes/styles to remove
			@sToggle: 	STRING, add/remove, defaults to 'add'
			@sType:	STRING, 
		*/
			console.log(sEl);
			var $el = $(sEl),
				tog = sToggle || 'add',
				klass = aosKlass,
				type = sType || 'class',
				k = self.type_of(klass) == 'array' ? klass.join(',') : klass;

			if (type == 'class') {
				if (tog == 'add') {
					$el.addClass(k);
				} else {
					$el.removeClass(k);
				}
			} else if (type == 'style' && self.type_of(klass) == 'object') {
				for (var p in klass) {
					if (self.check_property(klass, p)) {
						$el.css(p, klass[p]);
					}
				}
				
			}
			
		};
		
		self.type_of = function(value) {
			/*
				Crockford typeOf() method
				http://javascript.crockford.com/remedial.html
			*/
	    var s = typeof value;
	    if (s === 'object') {
	        if (value) {
	            if (typeof value.length === 'number' &&
	                    !(value.propertyIsEnumerable('length')) &&
	                    typeof value.splice === 'function') {
	                s = 'array';
	            }
	        } else {
	            s = 'null';
	        }
	    }
	    return s;
		}
		
		return self;
	}
	
	/*
		FUNCTION: initCorners()
		rounded corner support 
	*/
	function initCorners(klass, tl, tr, bl, br) {
		var setting = {
			tl: { radius: tl || 0 },
			tr: { radius: tr || 0 },
			bl: { radius: bl || 10 },
			br: { radius: br || 10 },
			antiAlias: true
		}
		var _k = klass || 'roundedCorners';
		var k = _k.indexOf('.') != 0 && _k.indexOf('#') < 0 ? '.' + _k : _k;
		curvyCorners(setting, k);
	}
	
	/**
	 * Class power sliding panels
	 */
	function Slider () {
		/*
			OBJECT: oCurHover
				- holder object for sliding elements
		*/
		var oCurHover = {};

		/**
		 * returns opposite direction of string passed in, defaults to 'up'
		 */
		function returnOppDir(dir) {
			return dir == 'up' ? 'down' : 'up';
		}
		
		/**
		 * animates the top position of passed in element
		 * @param {STRING/OBJECT} soEl
		 * @param {STRING} sDir
		 * @param {OBJECT} oOpts
		 * @param {FUNCTION} fCb
		 */
		function opening (soEl, sDir, oOpts, fCb) {
			var $el = soEl,
				dir = sDir,
				opts = oOpts || {},
				cb = fCb;
				
			if (typeof soEl == 'string') {
				$el = $($el);
			}
			var _dir = dir.toLowerCase(),
				oSlideSettings = $.extend({ nsSpeed: 'slow', nOffset: 0, sEasing: 'easeOutQuart', bClosing: false }, opts),
				elHeight = $el.outerHeight(),
				upTarget = opts.nOffset > 0 && !oSlideSettings.bClosing ? elHeight + oSlideSettings.nOffset : !oSlideSettings.bClosing ? elHeight : 0,
				downTarget = _dir == 'down' ? opts.nOffset > 0 ? oSlideSettings.nOffset : 0 : 0,
				_y = _dir == 'up' ? -(upTarget) : downTarget;
			$el.stop().animate(
				{
					'top': _y
				}, 
				oSlideSettings.nsSpeed, 
				oSlideSettings.sEasing,
				function() {
					if (cb) cb();
				}
			);
		}

		self.slide = function (type, tabId, $child, $secChild, dir, nOffset, nsoSpeed, soEasing, cb) {
			/*
				type:		STRING, show/hide
				tabId:		STRING
				$child:	 	OBJECT, jQuery-fied object, first object to animate
				$secChild:	OBJECT, jQuery-fied object, second object to animate 
				dir:	 	STRING, up/down
				nOffset:	NUMBER/
				nsoSpeed:	NUMBER/STRING/OBJECT, speed of animation, defaults to 'fast'
										 if OBJECT - must contain 'first', 'second' as properties 
				soEasing:	STRING/OBJECT, easing of animation, defaults to 'easeOutQuad'
										 if OBJECT - must contain 'first', 'second' as properties 
			*/
			if (typeof oCurHover[tabId] != 'object') {
				oCurHover[tabId] = {};
			}
			var speed = { first: 'fast', second: 'fast' },
					easing = { first: 'easeOutQuad', second: 'easeOutQuad' };
			if (wtd.helpers.type_of(nsoSpeed) == 'object') $.extend(true, speed, nsoSpeed);
			if (wtd.helpers.type_of(soEasing) == 'object') $.extend(true, easing, soEasing);
						
			var t = type || 'show',
					firstAnime = t == 'show' ? $child : $secChild,
					secondAnime = t == 'show' ? $secChild : $child,
					nsSpeed = wtd.helpers.type_of(nsoSpeed) == 'object' ? speed.first : nsoSpeed || 'fast',
					nsSpeed2 = wtd.helpers.type_of(nsoSpeed) == 'object' ? speed.second : nsoSpeed,
					sEasing = wtd.helpers.type_of(soEasing) == 'object' ? easing.first : easing,
					sEasing2 = wtd.helpers.type_of(soEasing) == 'object' ? easing.second : sEasing,
					oCur = oCurHover[tabId];
			
			oCur.bFirstIsAnimating = true;
		
			
			opening(firstAnime, dir, { nOffset: nOffset, nsSpeed: nsSpeed, sEasing: sEasing }, function(e) {
				var oppDir = returnOppDir(dir);
				var offset = t == 'show' ? 0 : nOffset;
				var bIsClosing = t == 'show' ? false : true;
				oCur.bFirstIsAnimating = false;
				oCur.bSecondIsAnimating = true;
				if ($secChild != undefined) {
					secondAnime.addClass('d-block');
					// hack, but will do for now
					opening(secondAnime, oppDir, { nOffset: offset, nsSpeed: nsSpeed2, sEasing: sEasing2, bClosing: bIsClosing }, function() {
						oCur.bIsClosing = bIsClosing;
						oCur.bSecondIsAnimating = false;
						//disableLinks('none', tabId);
						var console_message = t == 'show' ? 'in second cb hover: ' : 'in second cb off: ';
						console.log(console_message, tabId, ' : ', oCur.bIsClosing);
						// the following is only used if the self.slide() is triggered via hover
						if (!oCur.bIsClosing && !oCur.bFirstIsAnimating && !oCur.bSecondIsAnimating && !oCur.bHoverOn) {
							// this means the hover off event did not get fired and the tabs are still open...so fix it
							setTimeout(function() {
								self.slide('hide', tabId, oCur.$child, oCur.$secChild, dir, oCur.nOffset);
							}, 0);
						}
					});
				}
			});
			if (cb) cb();
		};
		
		self.init = function(oOpts) {

		};
		return self;
	}
	
	function ToggleScrollLink(type) {
		if (type != undefined) {
			var t = type == 'show' ? 'show' : 'hide';
			var $s = $('#scroll-link');
			if (type == 'show') $s.removeClass('d-none').addClass('d-block');
			else $s.removeClass('d-block').addClass('d-none');
			$s.click(function(e) {
				$s.removeClass('d-block').addClass('d-none');
				$win.scrollTo(0, 'slow', { easing: 'easeOutQuad' }).unbind('scrollTo');
			});
		}
	}
	
	$(function() {
		
		
		if (!$.support.boxModel) {
			initCorners('roundedCorners');
			initCorners('about-corners', 10, 10, 10, 10);
			initCorners('wrap-corners');
			initCorners('borders', 5, 5, 5, 5);
		}


		var curTab = '',
				rand = wtd.helpers.return_random_quad(),
				bgH = $header.height(),
				navH = $nav.height(),
				topOffset = bgH + navH,
				bgPos =  rand < 4 ? rand * bgH : 0,
				showEls = ['#projects-wrap', '#nav a span', '.project-tab a span', '#' + headerId + ' h1'],
				showElsLen = showEls.length
				$tab = $('#nav a span, .project-tab a span'),
				cur = '';
		$header.css({ 'background-position': '0 -' + bgPos + 'px', 'visibility': 'visible' });
		for (showElsLen; showElsLen--;) {
			wtd.helpers.toggle_classes(showEls[showElsLen], { visibility: 'visible' }, 'add', 'style');
		}
		
		wtd.fns.slider.init();
				
		$tab.click(function(e) {
			e.preventDefault();
			var $this = $(this),
					$par = $this.parents('li'),
					pId = '#' + $par.attr('id');
					
			console.log('pId: ', pId)
			
			if (pId.indexOf('n-') == 1) {
				pId = pId.replace('n-', 'p-');
			}
			
			var $p = $(pId);
			
			console.log(pId, ' : ', $(pId));

			/*
				type:		STRING, show/hide
				tabId:		STRING
				$child:	 	OBJECT, jQuery-fied object, first object to animate
				$secChild:	OBJECT, jQuery-fied object, second object to animate 
				dir:	 	STRING, up/down
				nOffset:	NUMBER, 
				nsSpeed:	NUMBER/STRING, speed of animation, defaults to 'fast'
			*/

			var tabId = pId,
					$child = $p,
					$secChild = $(cur).length > 0 ? $(cur) : undefined,
					$curTabInfo = $p.find('.project-info'),
					type = cur == '' ? 'show' : 'hide',
					dir = cur == '' ? 'down' : 'up',
					nOffset = navH + 6,
					nsSpeed = 'fast',
					soEasing = { },
					pH = $p.height(),
					rH = topOffset + pH,
					off = $curTabInfo.offset();

			staticLeft = off.left// + $curTabInfo.outerWidth(); // - 12; //- 27;

			$content.height(rH);
			$wrapper.height(rH);
			
			wtd.fns.slider.slide(type, tabId, $child, $secChild, dir, nOffset, nsSpeed, soEasing, function() { });
			cur = curTab = tabId;
			return false;
			
		});

		setTimeout(function() {
			var pChild = $projects.children('.project'),
				nHeight = 0;
			for (var i = pChild.length; i--;) {
				var $c = $(pChild[i]),
					h = $c.height();
				console.log($c, ' : ', h);	
				$c.css({ 'top': -(h), visibility: 'visible' });
			}

			var $resp = $('#result-response');
	
			if ($resp.length > 0) {
				cur = curTab = '#p-about';
				var nOffset = navH + 6,
					nsSpeed = 'fast',
					nsEasing = {},
					$p = $(cur),
					pH = $p.height(),
					rH = topOffset + pH;
				$wrapper.height(rH);
				wtd.fns.slider.slide('show', cur, $p, null, 'down', nOffset, nsSpeed, nsEasing, function() { console.log('sent') });
			}
		}, 1000);

		$win.scroll(function(e) {
			if (curTab != '') {
				var $curTabInfo = $(curTab).find('.project-info'),
					off = $curTabInfo.offset(),
					left = off.left,
					sh = $win.scrollTop(),
					bNeedsOffset = sh > topOffset ? true : false;
				if (bNeedsOffset) {
					$curTabInfo.css('left', staticLeft).addClass('info-fixed');
				} else {
					$curTabInfo.removeClass('info-fixed');
				}
			}
		});
		
	});
	
})(jQuery);

Cufon.set('fontFamily', 'champagne')
Cufon.replace('h1', {
	color: '-linear-gradient(#c995e5, .5=#8842e5, #c995e5)' //9e11e5
});  
Cufon.replace('#nav li a span', {
	hover: true
});
Cufon.replace('#projects-nav li a span', {
	hover: true
});
Cufon.now();

