/* Author: Jake Barrow
   Date: 12/18/2011
*/

jQuery(function($) {
	var Engine = {
		utils : {
			browserCss : function(){
				// lets do some browser detection and apply some classes accordingly. this gives us a simple hook for targeting browsers without the need for css hacks or additional .css files
				var putHere = $("html"),
					curBrowser;
				
				if($.browser.msie){
					curBrowser = "ie";
					putHere.addClass("ie"+parseInt($.browser.version,10)+" no-js");
					// if a layer (like autocomplete) goes beyond the viewport IE will add back in body scrollbars to accomodate. This forces the height so it can't do that. Doesn't work in IE9, reevaluate when it (IE9) goes to beta
					$(window).bind("resize",function(){
						$("body").height($(window).height());
					});
				}
				if($.browser.webkit){
					curBrowser = "webkit";
				}
				if($.browser.mozilla){
					curBrowser = "mozilla";
				}
				putHere.addClass(curBrowser);
			},
			lowerCaseH1 : function(){
				$('h1:contains("w/")').each(function(){
					$(this).html($(this).text().replace(/w\//g,'<span class="lowercase">w/</span>'));					  
				});
			},
			lastItem : function(){
				$('ul li:last-child').addClass('last');
			},
			/*videoJS : function(){
				var myManyPlayers = VideoJS.setup("All");
			},*/
			localVideo : function(){
				/*$('.localVideo').each(function(){
					// set popup size by adding to the video dimensions
					var vmargin = 0,
						vlink = $(this).attr('href'),
						w1 = vlink.indexOf('width=')+6,
						w2 = vlink.indexOf('&height'),
						h1 = w2+8,
						vwidth = parseInt(vlink.substring(w1,w2))+parseInt(vmargin),
						vheight = parseInt(vlink.substring(h1))+parseInt(vmargin),
						vhref= vlink.substring(0,w1)+vwidth+'&height='+vheight;
					$(this).attr('href',vhref);
				});*/
			},
			emailLinks : function(){
				// mail lilnks with /at/ 
				$('a[href^="mailto:"]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() === mail) {
						$(this).text(replaced);
					}
				});
			},
			breadcrumbs : function(){
				if($('.prependBC').length){
					var text = $('.prependBC').html();
					$('div.breadcrumbs').prepend(text);
					$('.prependBC').remove();	
				}
				if($('.replaceBC').length){
					var text = $('.replaceBC').html();
					$('div.breadcrumbs').html(text);
					$('.replaceBC').remove();
				}
				if($('.appendBC').length){
					var text = $('.appendBC').html();
					$('div.breadcrumbs').append(text);
					$('.appendBC').remove();
				}
				/*if($('div.breadcrumbs a:first:not([href="/"])').length){
					$('div.breadcrumbs').prepend('<a href="/" class="ir">Home</a>');
				}else if($('div.breadcrumbs a').length){
					$('.breadcrumbs a:[href="/"]').addClass('ir');	
				}else{
					$('div.breadcrumbs').prepend('<a href="/" class="ir">Home</a>');
				}*/
				$('.breadcrumbs a').each(function(){
					if($(this).text()=="Home"){
						$(this).addClass('ir');
					}
				});
				/*if($('.homePage .breadcrumbs').length){
					$('.breadcrumbs').remove();
				}*/
				$('div.breadcrumbs').contents().each(function(){
					if (this.nodeType === 3) {
						//alert($(this).text()+'**'+$.trim(this.textContent).length+'**'+/[^0-9a-zA-Z]+/.test(this.textContent));
						if($.trim(this.textContent).length<3){// && /[^0-9a-zA-Z]+/.test(this.textContent)
							$(this).remove();
						}else{
							$(this).wrap('<span/>');
						}
						//$(this).replaceWith('<span>'+$.trim(this.textContent)+'</span>')
					}
				});
			},
			blogSelected : function(){
				if($('.blog-overall').length>0){
					// set the selection in the secondary nav menu
					$('nav.secondary a[href^="/_blog"]').parent('li').addClass('selected');	
					
					// setup the breadcrumb and sidebar selected states depending on the type of page viewed
					if(window.location.href.indexOf('/tag/')!==-1){ // if individual tag was selected
						var t1 = window.location.href.indexOf('/tag/')+5,
							tag1 = window.location.href.substring(t1),
							t2 = tag1.indexOf('/'),
							tag = tag1.substring(0,t2),
							text = '<span>'+tag.replace(/_/g,' ')+'</span>';
						$('div.breadcrumbs').append(text); // append to the breacrumb
						$('.side-panel .BlogTagList a').each(function(){ // set the selected class on the anchor
							var thisHref = $(this).attr('href').toLowerCase();
							if(thisHref==getRelUrl(window.location.href)){
								$(this).parent('li').addClass('selected');
							}
						});
					}else if(window.location.href.indexOf('/post/')!==-1){ // if recent post was selected
						var t1 = window.location.href.indexOf('/post/')+6,
							tag1 = window.location.href.substring(t1),
							t2 = tag1.indexOf('/'),
							tag = tag1.substring(0,t2),
							text = '<span>'+tag.replace(/_/g,' ')+'</span>';
						$('div.breadcrumbs').append(text); // append to the breacrumb
						$('.side-panel .BlogRecentPost a').each(function(){ // set the selected class on the anchor
							var thisHref = $(this).attr('href').toLowerCase();
							if(thisHref==getRelUrl(window.location.href)){
								$(this).parent('li').addClass('selected');
							}
						});
					}else if(window.location.href.indexOf('/calendar/')!==-1){ // if archive month was selected
						var t1 = window.location.href.indexOf('/calendar/')+10,
							tag1 = window.location.href.substring(t1),
							t2 = tag1.indexOf('/'),
							year = tag1.substring(0,t2),
							tag2 = tag1.substring(t2+1),
							t3 = tag2.indexOf('/'),
							month = monthList[parseInt(tag2.substring(0,t3))-1],
							text = '<span>'+month+' '+year+'</span>';
						$('div.breadcrumbs').append(text); // append to the breacrumb
						$('.side-panel .BlogPostArchive a').each(function(){ // set the selected class on the anchor
							var thisHref = $(this).attr('href').toLowerCase();
							if(thisHref==getRelUrl(window.location.href)){
								$(this).parent('li').addClass('selected');
							}
						});
					}
				}
			},
			blogAuthors : function(){
				if($('.blog-overall').length>0){
					// set up the Authors section of the sidebar
					var authorList = {},
						authorCount = 0;
					// build the list of authors
					$('.blog-post footer').each(function(){
						var authorImg = $(this).find('.authorImg').html(),
							authorName = $(this).find('.post-detail .author').text(),
							authorBio = $(this).find('.post-detail .authorBio').html();
						if(authorBio){
							var	pAt = authorBio.indexOf('@')+1,
								stringAt = authorBio.substring(pAt),
								pEnd = stringAt.indexOf(' '),
								tString = stringAt.substring(0,pEnd);
							
							if(pAt!==-1){
							   authorBio = authorBio.substring(0,pAt-1)+'<a href="https://twitter.com/#!/'+(tString!=''?tString:stringAt)+'" class="twitterLink" target="_blank">@'+(tString!=''?tString:stringAt)+'</a>'+(tString!=''?stringAt.substring(pEnd):'');
							}
						}
						if (authorName){
							authorList[authorName] = new Array(authorImg,authorBio);
						}
						if(authorBio){
							$(this).find('.post-detail .authorBio').html(authorBio)
						}else{
							$(this).find('.post-detail .authorBio').hide();
						};
					});
					// add each author to the right column
					$.each(authorList,function(index, value) {
						$('.blog-overall .side-panel .authors').append(
							'<div class="author clearfix"><div class="authorImg">'+value[0]+'</div><h5 class="authorDetail">'+index+(value[1]?'<br/>'+value[1]:'')+'</h5></div>'
						);	
						authorCount++;
					});
					// show the authors if there are any
					if(authorCount>0){
						$('.blog-overall .side-panel .authors').show();
					}		
				}
			},
			blogPreview : function(){
				if($('.blog-overall').length>0){
					// pull the View More link out of the body overview and place on next line
					$('.post-body a:contains("Read More")').each(function(){
						$(this).insertAfter($(this).parent()).wrap('<p class="moreLink"/>');
					});
				}
			},
			readFeed : function(){
				if($('#latestNews').length){
					$('#latestNews').rssfeed('http://help.worldsecuresystems.com/RSSRetrieve.aspx?ID=74&Type=RSS20', {
						limit: 3,
						time: false,
						header: false,
						snippet: false,
						ppGroup: 'news',
						ppGroupH: 300,
						ppGroupW: 600
					},function(){
						Engine.utils.fancybox();	
					});
				}
				if($('#featuredPosts').length){
					$('#featuredPosts').rssfeed('http://pivoweb.com/RSSRetrieve.aspx?ID=11428&Type=RSS20', {
						limit: 3,
						time: false,
						header: false,
						snippet: false
					});
				}
			},
			overviewTabs : function(){
				if($('#overviewDetail').length){// && $('.ie8').length==0
					$('#overviewTabs li a').click(function(event) {
						event.preventDefault();
						var $anchor = $(this);
						$('#overviewDetail').fadeOut(200,function(){
							$('#main .loadingImg').show();
							/*$('#overviewDetail').load($anchor.attr('href')+' #description',function(){
								// new content loaded
								var newHeight = $('#overviewDetail').outerHeight();
								$('.dynamicContent').animate({ // animate new height of parent container
									height: newHeight
									}, 400, function() {
									$('#main .loadingImg').hide(); // hide the loading image
									$('#overviewDetail').fadeIn(300); // Fade in new content
								});
							});*/
							$.get($anchor.attr('href'),function(data){//+' #description'
								// new content loaded
								$('#overviewDetail').html(data);
								Engine.utils.fancybox();
								var newHeight = $('#overviewDetail').height();
								$('.dynamicContent').animate({ // animate new height of parent container
									height: newHeight
									}, 400, function() {
									$('#main .loadingImg').hide(); // hide the loading image
									$('#overviewDetail').fadeIn(300); // Fade in new content
								});
							});
							// set current tab class and remove sibling classes
							$anchor.parent('li').addClass('selected');
							$anchor.parent('li').siblings().removeClass('selected');
						});
					});
					// if there's a hash compare the string that follows with each of tab's href
					var hrefP = window.location.href.indexOf('#');
					if(hrefP!==-1){
						$('#overviewTabs li a[href*="'+window.location.href.substring(hrefP+1)+'"]').click();	
					}else{
						$('#overviewTabs li a:first').click();
					}
				}
			},
			testimonial : function(){
				if($('.pullQuote').length>0){
					$('.pq-img img').unwrap();
				}
			},
			fancybox : function(){
				if($("a.fbFrame").length > 0) {
					$("a.fbFrame:not(.ready)").each(function(){
						$(this).addClass('ready');
						var vmargin = 10,
							vlink = $(this).attr('href'),
							self = $(this),
							w1 = vlink.indexOf('width=')+6,
							w2 = vlink.indexOf('&height'),
							h1 = w2+8,
							h2 = vlink.indexOf('&link'),
							l1 = h2+6,
							vwidth = parseInt(vlink.substring(w1,w2))+parseInt(vmargin),
							vheight = parseInt(vlink.substring(h1,h2))+parseInt(vmargin),
							relGroup = $(this).attr('rel'),
							linkType = vlink.substring(l1);
						if(h2!==-1){	
							switch(linkType){
								case 'Image': // if an image link, remove the BC anchor and insert the image into the popup anchor
								//self.empty(); // remove any text link markup
								self.next('a[href*="popup"]').find('img').unwrap().appendTo(self);
								self.next('.textLink').remove();
								break;
								case 'Text-Link': // if a text link, remove the image link if any
								self.next('a[href*="popup"]').remove();
								break;
								case 'Text-Button': // if a text link, remove the image link if any
								self.addClass('button');
								self.next('a[href*="popup"]').remove();
								break;
								default:
								self.next('a[href*="popup"]').remove();
								if(self.next('.textLink').text()==''){
									self.next('.textLink').text('Learn More');
								}
							}
						}
						if(relGroup==''){
							self.attr('rel','fbGroup');	
						}
							
						$(this).fancybox({
							'width'			: vwidth,
							'height'		: vheight,
							'overlayOpacity': 0.7,
							'centerOnScroll': true,
							'overlayColor' 	: '#333',
							'autoDimensions': false,
							'transitionIn'	: 'elastic',
							'transitionOut'	: 'elastic',
							'speedIn'		: 400,
							'speedOut'		: 400,	
							'easingIn'		: 'easeOutQuad',
							'easingOut'		: 'easeOutQuad',
							'type'			: 'iframe'
							//closeBtn	: true
						});
					});
				}				
				if($("a.fbAjax").length > 0) {
					$("a.fbAjax:not(.ready)").each(function(){
						$(this).addClass('ready');						
						// get the link type from the 'link' URL parameter						
						var vlink = $(this).attr('href'),
							t1 = vlink.indexOf('?link=')+6,
							self = $(this),
							relGroup = $(this).attr('rel'),
							linkType = vlink.substring(t1);
						
						switch(linkType){
							case 'Image': // if an image link, remove the BC anchor and insert the image into the popup anchor
							//self.empty(); // remove any text link markup
							self.next('a[href*="local-content-popup"]').find('img').unwrap().appendTo(self);
							self.next('.textLink').remove();
							break;
							case 'Text-Link': // if a text link, remove the image link if any
							self.next('a[href*="local-content-popup"]').remove();
							break;
							case 'Text-Button': // if a text link, remove the image link if any
							self.addClass('button');
							self.next('a[href*="local-content-popup"]').remove();
							break;
							default:
							self.next('a[href*="local-content-popup"]').remove();
							if(self.next('.textLink').text()==''){
								self.next('.textLink').text('Learn More');
							}
						}
						if(relGroup==''){
							self.attr('rel','fbGroup');	
						}
							
							//vheight = parseInt(vlink.substring(h1))+parseInt(vmargin);
						self.fancybox({
							'overlayOpacity': 0.7,
							'centerOnScroll': true,
							'scrolling'		: 'auto',
							'overlayColor' 	: '#333',
							'autoDimensions': true,
							'transitionIn'	: 'elastic',
							'transitionOut'	: 'elastic',
							'speedIn'		: 400,
							'speedOut'		: 400,	
							'easingIn'		: 'easeOutQuad',
							'easingOut'		: 'easeOutQuad',
							'type'			: 'ajax'
						});
					});
				}				
			}
		},
		// END utils

		/*forms : {
			labels : function() {
				$('#search-form label').compactize();
				$('.form-b label').compactize();
			}
		},*/
		ui : {
			/*loginDialog : function(){
				$('.openLogin').click(function(e){
					e.preventDefault();
					$('#loginDialog').dialog({ 
						modal: true,
						title: 'Account Login',
						show: "blind"
					});
				});
			},
			
			tabs : function(){
				if($.ui.tabs){
					$('.tabs-wrapper').each(function(){
						var cur = $(this),
							taboptions,
							disabledtabs = [];
						
						taboptions = {};
						
						taboptions = $.extend(true,taboptions, cur.data("tabs-options"));
						// console.debug(taboptions);
						var tabs = cur.tabs(taboptions);
					});
				}
			},*/
			watermark : function(){
				// watermark placeholder setup
				if($.ui.watermark){
					$("input[type=password][placeholder],input[type=text][placeholder],input[type=email][placeholder],textarea[placeholder],input[type=search][placeholder]").watermark();
				}
			}
		}
		// End Widgets
	}
	// END ENGINE
	
	Engine.utils.browserCss();
	Engine.utils.emailLinks();
	Engine.utils.lastItem();
	Engine.utils.breadcrumbs();
	Engine.utils.readFeed();
	Engine.utils.overviewTabs();
	Engine.utils.fancybox();
	Engine.utils.lowerCaseH1();
	Engine.utils.testimonial();
	Engine.utils.blogSelected();
	Engine.utils.blogAuthors();
	Engine.utils.blogPreview();
	//Engine.utils.localVideo();
	/*Engine.ui.loginDialog();
	Engine.ui.tabs();*/
	Engine.ui.watermark();
});


/*UTIL = {
 
	fire : function(func,funcname, args){
 
		var namespace = engine;  // indicate your obj literal namespace here
	 
		funcname = (funcname === undefined) ? 'init' : funcname;
		if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
		  namespace[func][funcname](args);
		} 
 
	}, 
 
  	loadEvents : function(){
 
		var bodyId = document.body.id;
	 
		// hit up common first.
		UTIL.fire('common');
	 
		// do all the classes too.
		$.each(document.body.className.split(/\s+/),function(i,classnm){
		  UTIL.fire(classnm);
		  UTIL.fire(classnm,bodyId);
		});
	 
		UTIL.fire('common','finalize');
	} 
}; 
// END UTIL



// kick it all off here 
$(document).ready(UTIL.loadEvents);*/

/* get URL parameters */
function gup( name )
{ 
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function getDomain(url){
var thisURL = url.toLowerCase(),
	p1 = (thisURL.indexOf("www.")!==-1?thisURL.indexOf("www.")+4:thisURL.indexOf("//")+2),
	tUrl1 = thisURL.substring(p1),
	p2 = tUrl1.indexOf('/'),
	tUrl2 = tUrl1.substring(0,p2);
	return tUrl2;
}
function getRelUrl(url){
var thisURL = url.toLowerCase(),
	p1 = (thisURL.indexOf("www.")!==-1?thisURL.indexOf("www.")+4:thisURL.indexOf("//")+2),
	tUrl1 = thisURL.substring(p1),
	p2 = tUrl1.indexOf('/'),
	tUrl2 = tUrl1.substring(p2);
	return tUrl2;
}
var monthListAbbr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var monthList = ['January','February','March','April','May','June','July','August','September','October','November','December'];
