// INITIALIZATION 
var indexServiceTransitionSpeed = 200;
var isSlideshowAdvancing        = false;

//fgnass.github.com/spin.js#v1.2.2
(function(a,b,c){function n(a){var b={x:a.offsetLeft,y:a.offsetTop};while(a=a.offsetParent)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}function m(a){for(var b=1;b<arguments.length;b++){var d=arguments[b];for(var e in d)a[e]===c&&(a[e]=d[e])}return a}function l(a,b){for(var c in b)a.style[k(a,c)||c]=b[c];return a}function k(a,b){var e=a.style,f,g;if(e[b]!==c)return b;b=b.charAt(0).toUpperCase()+b.slice(1);for(g=0;g<d.length;g++){f=d[g]+b;if(e[f]!==c)return f}}function j(a,b,c,d){var g=["opacity",b,~~(a*100),c,d].join("-"),h=.01+c/d*100,j=Math.max(1-(1-a)/b*(100-h),a),k=f.substring(0,f.indexOf("Animation")).toLowerCase(),l=k&&"-"+k+"-"||"";e[g]||(i.insertRule("@"+l+"keyframes "+g+"{"+"0%{opacity:"+j+"}"+h+"%{opacity:"+a+"}"+(h+.01)+"%{opacity:1}"+(h+b)%100+"%{opacity:"+a+"}"+"100%{opacity:"+j+"}"+"}",0),e[g]=1);return g}function h(a,b,c){c&&!c.parentNode&&h(a,c),a.insertBefore(b,c||null);return a}function g(a,c){var d=b.createElement(a||"div"),e;for(e in c)d[e]=c[e];return d}var d=["webkit","Moz","ms","O"],e={},f,i=function(){var a=g("style");h(b.getElementsByTagName("head")[0],a);return a.sheet||a.styleSheet}(),o=function r(a){if(!this.spin)return new r(a);this.opts=m(a||{},r.defaults,p)},p=o.defaults={lines:12,length:7,width:5,radius:10,color:"#000",speed:1,trail:100,opacity:.25,fps:20},q=o.prototype={spin:function(a){this.stop();var b=this,c=b.el=l(g(),{position:"relative"}),d,e;a&&(e=n(h(a,c,a.firstChild)),d=n(c),l(c,{left:(a.offsetWidth>>1)-d.x+e.x+"px",top:(a.offsetHeight>>1)-d.y+e.y+"px"})),c.setAttribute("aria-role","progressbar"),b.lines(c,b.opts);if(!f){var i=b.opts,j=0,k=i.fps,m=k/i.speed,o=(1-i.opacity)/(m*i.trail/100),p=m/i.lines;(function q(){j++;for(var a=i.lines;a;a--){var d=Math.max(1-(j+a*p)%m*o,i.opacity);b.opacity(c,i.lines-a,d,i)}b.timeout=b.el&&setTimeout(q,~~(1e3/k))})()}return b},stop:function(){var a=this.el;a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=c);return this}};q.lines=function(a,b){function e(a,d){return l(g(),{position:"absolute",width:b.length+b.width+"px",height:b.width+"px",background:a,boxShadow:d,transformOrigin:"left",transform:"rotate("+~~(360/b.lines*c)+"deg) translate("+b.radius+"px"+",0)",borderRadius:(b.width>>1)+"px"})}var c=0,d;for(;c<b.lines;c++)d=l(g(),{position:"absolute",top:1+~(b.width/2)+"px",transform:"translate3d(0,0,0)",opacity:b.opacity,animation:f&&j(b.opacity,b.trail,c,b.lines)+" "+1/b.speed+"s linear infinite"}),b.shadow&&h(d,l(e("#000","0 0 4px #000"),{top:"2px"})),h(a,h(d,e(b.color,"0 0 1px rgba(0,0,0,.1)")));return a},q.opacity=function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)},function(){var a=l(g("group"),{behavior:"url(#default#VML)"}),b;if(!k(a,"transform")&&a.adj){for(b=4;b--;)i.addRule(["group","roundrect","fill","stroke"][b],"behavior:url(#default#VML)");q.lines=function(a,b){function k(a,d,i){h(f,h(l(e(),{rotation:360/b.lines*a+"deg",left:~~d}),h(l(g("roundrect",{arcsize:1}),{width:c,height:b.width,left:b.radius,top:-b.width>>1,filter:i}),g("fill",{color:b.color,opacity:b.opacity}),g("stroke",{opacity:0}))))}function e(){return l(g("group",{coordsize:d+" "+d,coordorigin:-c+" "+ -c}),{width:d,height:d})}var c=b.length+b.width,d=2*c,f=e(),i=~(b.length+b.radius+b.width)+"px",j;if(b.shadow)for(j=1;j<=b.lines;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;j<=b.lines;j++)k(j);return h(l(a,{margin:i+" 0 0 "+i,zoom:1}),f)},q.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}}else f=k(a,"animation")}(),a.Spinner=o})(window,document);

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an elipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
function truncate(text, length, ellipsis) { 
	if (typeof length == 'undefined') var length = 100;
	if (typeof ellipsis == 'undefined') var ellipsis = '...';
	if (text.length < length) return text;
	for (var i = length-1; text.charAt(i) != ' '; i--) {
		length--;
	}
	return text.substr(0, length) + ellipsis;
}

(function(k,e,i,j){k.fn.caret=function(b,l){var a,c,f=this[0],d=k.browser.msie;if(typeof b==="object"&&typeof b.start==="number"&&typeof b.end==="number"){a=b.start;c=b.end}else if(typeof b==="number"&&typeof l==="number"){a=b;c=l}else if(typeof b==="string")if((a=f.value.indexOf(b))>-1)c=a+b[e];else a=null;else if(Object.prototype.toString.call(b)==="[object RegExp]"){b=b.exec(f.value);if(b!=null){a=b.index;c=a+b[0][e]}}if(typeof a!="undefined"){if(d){d=this[0].createTextRange();d.collapse(true);
d.moveStart("character",a);d.moveEnd("character",c-a);d.select()}else{this[0].selectionStart=a;this[0].selectionEnd=c}this[0].focus();return this}else{if(d){c=document.selection;if(this[0].tagName.toLowerCase()!="textarea"){d=this.val();a=c[i]()[j]();a.moveEnd("character",d[e]);var g=a.text==""?d[e]:d.lastIndexOf(a.text);a=c[i]()[j]();a.moveStart("character",-d[e]);var h=a.text[e]}else{a=c[i]();c=a[j]();c.moveToElementText(this[0]);c.setEndPoint("EndToEnd",a);g=c.text[e]-a.text[e];h=g+a.text[e]}}else{g=
f.selectionStart;h=f.selectionEnd}a=f.value.substring(g,h);return{start:g,end:h,text:a,replace:function(m){return f.value.substring(0,g)+m+f.value.substring(h,f.value[e])}}}}})(jQuery,"length","createRange","duplicate");
function valueIsDefault(o) {
	if ( o.val() == o.attr("defaultValue") ) {
		return true;
	} else {
		return false;
	}
}
/* jFeed : jQuery feed parser plugin
 * Copyright (C) 2007 Jean-François Hovinne - http://www.hovinne.com/
 * Dual licensed under the MIT (MIT-license.txt)
 * and GPL (GPL-license.txt) licenses.
 */
function JFeedItem() {};
JFeedItem.prototype = {
	title: '',
	link: '',
	description: '',
	updated: '',
	id: ''
};
function JAtom(xml) {
	this._parse(xml);
};
JAtom.prototype = {
	_parse: function(xml) {
		var channel = jQuery('feed', xml).eq(0);
		this.version = '1.0';
		this.title = jQuery(channel).find('title:first').text();
		this.link = jQuery(channel).find('link:first').attr('href');
		this.description = jQuery(channel).find('subtitle:first').text();
		this.language = jQuery(channel).attr('xml:lang');
		this.updated = jQuery(channel).find('updated:first').text();
		this.items = new Array();
		var feed = this;
		jQuery('entry', xml).each( function() {
			var item = new JFeedItem();
			item.title = jQuery(this).find('title').eq(0).text();
			item.link = jQuery(this).find('link').eq(0).attr('href');
			item.description = jQuery(this).find('content').eq(0).text();
			item.updated = jQuery(this).find('updated').eq(0).text();
			item.id = jQuery(this).find('id').eq(0).text();
			feed.items.push(item);
		});
	}
};
function JRss(xml) {
	this._parse(xml);
};
JRss.prototype  = {
	_parse: function(xml) {
		if(jQuery('rss', xml).length == 0) this.version = '1.0';
		else this.version = jQuery('rss', xml).eq(0).attr('version');
		var channel = jQuery('channel', xml).eq(0);
		this.title = jQuery(channel).find('title:first').text();
		this.link = jQuery(channel).find('link:first').text();
		this.description = jQuery(channel).find('description:first').text();
		this.language = jQuery(channel).find('language:first').text();
		this.updated = jQuery(channel).find('lastBuildDate:first').text();
		this.items = new Array();
		var feed = this;
		jQuery('item', xml).each( function() {
			var item = new JFeedItem();
			item.title = jQuery(this).find('title').eq(0).text();
			item.link = jQuery(this).find('link').eq(0).text();
			item.description = jQuery(this).find('description').eq(0).text();
			item.updated = jQuery(this).find('pubDate').eq(0).text();
			item.id = jQuery(this).find('guid').eq(0).text();
			feed.items.push(item);
		});
	}
};
jQuery.getFeed = function(options) {
	options = jQuery.extend({
		url: null,
		data: null,
		success: null
	}, options);
	if(options.url) {
		$.ajax({
			type: 'GET',
			url: options.url,
			data: options.data,
			dataType: 'xml',
			success: function(xml) {
				var feed = new JFeed(xml);
				if(jQuery.isFunction(options.success)) options.success(feed);
			}
		});
	}
};
function JFeed(xml) {
	if(xml) this.parse(xml);
};
JFeed.prototype = {
	type: '',
	version: '',
	title: '',
	link: '',
	description: '',
	parse: function(xml) {
		if(jQuery('channel', xml).length == 1) {
			this.type = 'rss';
			var feedClass = new JRss(xml);
		} else if(jQuery('feed', xml).length == 1) {
			this.type = 'atom';
			var feedClass = new JAtom(xml);
		}
		if(feedClass) jQuery.extend(this, feedClass);
	}
};
function HubSpotFormSpamCheck_LeadGen_ContactForm_32444_m0() {
	var form = $("#connect form");
	var data = form.serialize()+"&mode=collaborate20110601";
	form.find(":input").each( function() {
		$(this).attr("disabled","disabled");
		if ( $(this).is(":submit") ) {
			$(this).value="sending...";
			$(this).addClass("disabled");
		}
	});
	var url  = 'http://www.i-designs.ca/2011/ajax';
	var result = $.ajax({
		success: function() {
			var form = $("#connect form");
			form.find(":input").each( function() {
				$(this).removeAttr("disabled");
				if ( $(this).is(":submit") === true ) {
					$(this).value="Email Sent";
					$(this).removeClass("disabled");
				}
			});
			// Hubspot
			var key = document.getElementById('LeadGen_ContactForm_32444_m0spam_check_key').value;
			var sig = '';
			for (var x = 0; x< key.length; x++ ) {
				sig += key.charCodeAt(x)+13;
			}
			document.getElementById('LeadGen_ContactForm_32444_m0spam_check_sig').value = sig; 
			var results = document.cookie.match ( '(^|;) ?hubspotutk=([^;]*)(;|$)' );
			if (results && results[2]) {
				document.getElementById('LeadGen_ContactForm_32444_m0submitter_user_token').value =  results[2];
			} else if (window['hsut']) {
				document.getElementById('LeadGen_ContactForm_32444_m0submitter_user_token').value = window['hsut'];
			}
			return true;                
		},
		url   : url, 
		async : false,  
		data  : data
	});
	return result;
}
function highlightIndexNav() {
	if ( $("#body-index").length <= 0 ) {
		return;
	}
	var top = $("body > nav").offset().top;
	$("body > section").each( function() {
		var scrollTop    = $(this).offset().top;
		var scrollBottom = $(this).offset().top - $(this).height();
		if ( scrollTop >= top && scrollBottom <= top ) {
			var sectionID = $(this).attr("id");
			$("body > nav a").each( function() {
				if ( $(this).text().toLowerCase() == sectionID ) {
					$(this).addClass("active");
				} else {
					if ( $(this).hasClass("active") ) {
						$(this).removeClass("active");
					}
				}
			});
			if ( "services" == sectionID ) {
				$("body > nav").css({
					'width'      : '100%',
					'marginLeft' : '0',
					'left'       : '0'
				});
			} else {
				$("body > nav").css({
					'width'      : '980px',
					'marginLeft' : '-490px',
					'left'       : '50%'   
				});
			}
		} else {     
			// not within a section
			if ( $(window).scrollTop() + $(window).height() > $(document).height() - 400 ) {
				var sectionID = "contact";
				$("body > nav a").each( function() {
					if ( $(this).text().toLowerCase() == sectionID ) {
						$(this).addClass("active");
					} else {
						if ( $(this).hasClass("active") ) {
							$(this).removeClass("active");
						}
					}
				});                  
			}
		}
	});
}
function setSectionMinHeight(elem) {
	var height = elem.height();
	var width  = elem.width();
	var resizeElements = "body > section, body > footer";
	$(resizeElements).css({
		'width'             : width
		,'height'           : height
	});
}
function advance(direction) {
	if ( true === isSlideshowAdvancing ) {
		// do nothing
	} else {
		isSlideshowAdvancing = true;
		var container        = $("#project-highlights .container");
		var ANIMATE_SPEED    = 400;
		if ( container.children().size() < 2 ) {
			return;
		}
		var firstChild   = container.find("li:first-child");
		var newChild     = false;
		var lastChild    = container.find("li:last-child");
		var widthOfLi    = firstChild.outerWidth() + 'px';
		var negWidthOfLi = '-' + widthOfLi;
		switch( direction ) {
			case "left":
				newChild = lastChild;
				firstChild.before(lastChild);
				container.css({'marginLeft':negWidthOfLi}).animate({'marginLeft':0,'height':newChild.outerHeight()},ANIMATE_SPEED,"swing", function() {
					isSlideshowAdvancing = false;
				});
				break;
			case "right":
				newChild = container.find("li:first-child").next();
				container.animate({'marginLeft':negWidthOfLi,'height':newChild.outerHeight()},ANIMATE_SPEED,"swing", function() {
					lastChild.after(firstChild);
					$(this).css({'marginLeft':0});
					isSlideshowAdvancing = false;
				});
				break;
			default:
				break;
		}
	}
	return;   
}

$(document).ready( function() {
	//setSectionMinHeight($(window));
	// INDEX NAVIGATION
	/* highlightIndexNav();
	$(window).scroll( function() {
		highlightIndexNav();     
	});
	*/
	$("#services nav li a").hover( function() {
		if ( true === $(this).hasClass("active") ) {
			// do nothing
		} else {
			$("#services nav li a").each( function() {
				if ( true === $(this).hasClass("active") ) {
					$(this).removeClass("active");
					var index = $(this).parents("li").index() + 1;
					$("#service-container section:nth-child("+index+")").stop(true,true).fadeOut(indexServiceTransitionSpeed);
				}    
			});
			$(this).addClass("active");
			var index = $(this).parents("li").index() + 1;
			$("#service-container section:nth-child("+index+")").stop(true,true).fadeIn(indexServiceTransitionSpeed);
		}   
	});
	/*
	$(".tpl-2 body > nav ol a").click( function(e) {
		e.preventDefault();
		var href = $(this).attr("href");
		var target = 0;
		if ( href === "#services" ) {
			target = 0;
		} else {
			target = $(href).offset().top - 150;
		}
		$('html, body').animate({scrollTop: target}, 300);
	});
	$(".tpl-2 body > nav .centered > a").click( function(e) {
		e.preventDefault();
		var target = 0;
		$('html, body').animate({scrollTop: target}, 300);        
	});
	*/
	$('.blog-listing .summary-link').click( function(e) {
		e.preventDefault();
		$('html,body').animate({scrollTop: $('#about').offset().top},300);
	});
	
	// TWITTER
	$("#tweets").tweet({
		username: ["lean_tobe_green"], // ["idesignsinc", "lean_tobe_green"]
		count: 3,
		fetch: 30,
		template: "<li>{text}{time}</li>",
		loading_text: "loading..."
	});
	
	// INPUT UX
	$("input:text,input[type=email]").click( function() {
		valueIsDefault($(this)) ? $(this).caret(0,0) : $.noop();
		$(this).hasClass("focus") === false && $(this).val() == $(this).attr("defaultValue") ? $(this).addClass("focus") : $.noop();    
	}).keydown ( function(e) {
		var BACKSPACE_KEY_CODE = 8;
		var SHIFT_KEY_CODE     = 16;
		if ( e.which == SHIFT_KEY_CODE ) {
			// do nothing
		} else if ( e.which == BACKSPACE_KEY_CODE ) {
			if ( $(this).val().length == 1 ) {
				var temp = $(this).attr("defaultValue");
				$(this).val(temp).addClass("focus").caret(0,0);
			}
		} else {
			valueIsDefault($(this)) ? $(this).val("") : $.noop();
			var hasClass = $(this).hasClass("focus") ? true : false;
			var isBlank  = $(this).val() === "" ? true : false;
			if ( true === hasClass && true === isBlank ) {
				// do nothing
			} else if ( true === hasClass && false === isBlank ) {
				$(this).removeClass("focus");
			} else if ( false === hasClass && true === isBlank ) {
				$(this).addClass("focus");
			} else if ( false === hasClass && false === isBlank ) {
				// do nothing
			}
			if ( false === valueIsDefault($(this)) && $(this).hasClass("focus") ) {
				$(this).removeClass("focus");
			}            
		}

	}).blur ( function() {
		$(this).val() === "" ? $(this).val($(this).attr("defaultValue")) : $.noop();
		$(this).hasClass("focus") ? $(this).removeClass("focus") : $.noop();
	});
		
	// DIALOG
	var page = $("body").attr("id");
	switch ( page ) {
		case "body-thanks":
			$("body").append("<a href='http://www.i-designs.ca/2011/dialog?message=thanks' class='dialog' style='display: none;' id='dialog-link'></a>");
			break;
	}
	$("a.dialog").fancybox({
		'padding'          :    '10',
		'transitionIn'     :    'fade',
		'transitionOut'    :    'fade',
		'speedIn'          :    400, 
		'speedOut'         :    200, 
		'overlayOpacity'   :    '0.8',
		'overlayColor'     :    '#fff'  
	});
	$("#dialog-link").click().detach();
	/* $(window).resize( function() {
		setSectionMinHeight($(this));
	}); */
	
	// FORM SUBMISSION
	$('form').submit( function(e) {
		if ( 'request-more-information' == $(this).children('[name="mode"]').val() ) {
			e.preventDefault();
			var opts = {
				lines   : 12, // The number of lines to draw
				length  : 7, // The length of each line
				width   : 3, // The line thickness
				radius  : 6, // The radius of the inner circle
				color   : '#000', // #rgb or #rrggbb
				speed   : 1, // Rounds per second
				trail   : 61, // Afterglow percentage
				shadow  : false // Whether to render a shadow
			};
			var target = document.getElementById('response');
			var spinner = new Spinner(opts).spin(target);
			var method = $(this).attr("method");
			var action = $(this).attr("action");
			var query  = $(this).serialize();
			$(this).children('input').each ( function() {
				$(this).attr("disabled","disabled");
			});
			var xhr    = $.ajax({
				url         : action
				,method     : 'http://www.i-designs.ca'/+action
				,dataType   : 'html'
				,data       : query
				,success    : function( data, status, xhr ) {
					if ( true === $('html').hasClass('page-blog') ) {
						xhr.form.fadeOut("fast");
						$('.premium p').remove();
						$('.premium h2').text("Thank You for Getting In Touch with Us");
						$('.premium hgroup').after('<p>We will be getting in touch with you soon with your premium content.</p>');
					} else if ( true === $('html').hasClass('tpl-13') ) {
						xhr.form.fadeOut("fast");
						$('.premium p').remove();
						$('.premium h1').text("Thank You for Getting In Touch with Us");
						$('.premium h1').after('<p>We will be getting in touch with you soon with your premium content.</p>');
					} else {
						xhr.stopWorking("Request received!");
						xhr.clearForm();
						xhr.enableForm();
					}
				}
				,error      : function( data, status, xhr ) {
					xhr.stopWorking("Error, try again.");
					xhr.enableForm();
				}
			});
			xhr.form = $(this);
			xhr.enableForm = function() {
				xhr.form.children("input").each( function() {
					$(this).removeAttr("disabled");
				});
			};
			xhr.clearForm  = function() {
				xhr.form.children('input:text,input[type="email"]').each ( function() {
					var defaultValue = $(this).attr("defaultValue");
					$(this).val( defaultValue );
				});
			};
			xhr.stopWorking  = function(response) {
				spinner.stop();
				$("#response").html(response);
			};
		}
	});
	$('.download a.button').click( function(e) {
		e.preventDefault();
		$(this).fadeOut("fast", function() {
			$('.download .request-more-information').fadeIn("fast");
		});                                                        
	});
	if ( $("#project-highlights").size() > 0 ) {
		var lengthOfLi       = $("#project-highlights .container li:first-child").width();
		var firstLiHeight    = $("#project-highlights .container li:first-child").height();
		var numberOfChildren = $("#project-highlights .container").children().size();
		var width            = lengthOfLi * numberOfChildren;
		$('#project-highlights .container').width(width);
		$('#project-highlights .container').height(firstLiHeight);
	}
	if ( $("#project-highlights .container").children().size() < 2 ) {
		$("#project-highlights > button").hide();
	} 
	$("#project-highlights > button").click( function() {
		var action = false;
		if ( true === isSlideshowAdvancing ) {
			return false;
		}
		if ( $(this).hasClass("left") ) {
			action = "left";
		} else if ( $(this).hasClass("right") ) {
			action = "right";
		}
		if ( false !== action ) {
			return advance(action);
		} else {
			return false;
		}
	});
});


