var positions = new Object();
var entries = new Array();
var tweetArray = new Array()
var activeFilter = '#all';
var modalcarousel = null;
var windowLocation = new Number();
var currSlide = 1;

var subscribeToNewsletter=function(){ 
	var response = new String()
	response = 'huh'
	$.ajax({
	type: "POST",
	url: "Subscribe.aspx",
	data: "{}",
	contentType: "application/json; charset=utf-8",
	dataType: "json",
	success: function(msg) {
		response = 'Thank you!'
	},
	404: function() {
    	response = 'Thank you!'
    },
	error: function(jqXHR, textStatus, errorThrown) {
		console.log('error :: js/edlibs/master.js :: subscribeToNewsletter()' + textStatus );
		response = 'Thank you!'
	},
	complete: function () {
		$('#maillist_subscribe').fadeOut(0);
		$('#maillist .arti p').empty()
		$('#maillist .arti p').append(response)
		}
	});
}

$(document).ready( function(){
	$("img").lazyload({
		placeholder : "img/white.gif",
		effect : "fadeIn"
	});
		
	//main navigation create tier 2 trigger nav roll overs
	if( $('#clientspane').length > 0 ) {
		$('#clientspane').load('clientspane.html', function() { 
			jQuery('#clientcarousel').jcarousel({
				wrap: 'circular',
				auto: 3.5,
				animation: 'slow',
				scroll: 4,
				initCallback: clientcarousel_initCallback,
				buttonNextHTML: null,
				buttonPrevHTML: null
			});
		});
	};
	addNav();
	addFooter();
	
	CheckModalNeed();
	CustomByCaseScenario();
	
	var htmldoc = new String();
	var tot = new Array();
	tot = String(window.location).split('/');
	htmldoc = tot[tot.length - 1];
	
	$(".pagecontent article nav").find("li").removeClass('active');
	$('[href=' + htmldoc + ']').parent().addClass('active');
	
	if(htmldoc == 'index.html#home' ) {
		$(QueryLoader.overlay).fadeOut(0);
		$(QueryLoader.preloader).remove();	
	}
});

function CreateCampaigns() {
	$.ajax({
        type: "GET",
		url: 'solutions/all_campaigns_data.xml',
		dataType: "xml",
		success: function(xml) {
			$(xml).find('item').each(function(){
				if( activeFilter == '#all' ) {
					AddCampaignItem($(this))
				} else {
					var catagories = new String();
					catagories = $(this).attr('catagory')
					var catagoryarr = new Array();
					catagoryarr = catagories.split(",")[1].split("|");
					$.each(catagoryarr, function(index, value) { 
						if( value == activeFilter ) {
							AddCampaignItem($(this))
						}
					});
				}
			});
		},
		404: function() {
			console.log('ajax get xml :: 404 ::');
		},
		error: function(jqXHR, textStatus, errorThrown) {
			console.log('ajax get xml :: fail :: ' + textStatus );
		}
	});
}

function addNav() {
	var nav = $("#navigation");
	var pageTitle = nav.html();
	nav.empty();
	
	nav.load('navigation.html', function(){
		SetUpNavDrops();
		var url = document.location.href;
		url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
		url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
		url = url.substring(url.lastIndexOf("/") + 1, url.length);
		$("#masterhead nav ul li a").each(function(){
			if( $(this).attr('href') == url ) {
				$(this).parent().addClass('active');
			} else {
				$(this).parent().removeClass('active');
			}
		});
		
		
		$('#pagetitle').append(pageTitle);
	})
};

function addFooter() {
	
	var htmldoc = new String();
	var tot = new Array();
	tot = String(window.location).split('/');
	htmldoc = tot[tot.length - 1];
	if(htmldoc == 'solution.html')
	{
		/*
		//animate blocks here
		var globaldelay = 500;
		var delayamt = 100;
		var fadetime = 400;
		$('.c_entry').each(function(index, eventTarget){
			$(eventTarget).fadeOut(0);
			$(eventTarget).delay(globaldelay + ( index * delayamt )).fadeIn(fadetime);
		});
		*/
		SetUpCampaignFiltering();
	}
	
	$("#footerblock").load('footer.html', function(){
		updateTwitter()	

		if(htmldoc == 'contact.html' ) {
			//don't show that 'view contact page' link on the contact page...
			$('#linktocontactpage').remove();
		}
		$('.userinput').click( function() {
			$(this).attr('value', '')
		});
		
		
	})
};

function CheckModalNeed(){
	//check for any need for modal window
	if( $('.c_entry').length > 0) {
		removeModalWindow();
		addModalWindow();
		$('#modalwindow').jqm({onShow:modalOnOpen, onHide:modalOnClose});
	} else {
		removeModalWindow();
	};	
};

function addModalWindow(){
	$('body').append(
	"<div class='jqmWindow' id='modalwindow'>" +
	"	<div id='modalclose'><a href='#' class='jqmClose'></a></div>" +
	"	<div class='modalcontainer'>" +
	"		<ul id='campaigncarousel' class='jcarousel-skin-camp'>" +
	"		</ul>" +
	"		<a href='#' id='mycarousel-prev' class='modalnavigatiorbutton'><div class='icon'></div></a>" +
	"		<a href='#' id='mycarousel-next' class='modalnavigatiorbutton'><div class='icon'></div></a>" +
	"		<div id='collection'><p></p></div>" +
	"		<header><h6 id='modalmaintitle'></h6></header>" +
	"		<div id='launchsite'><a href='#' target='_blank' class='lt'>Launch Site</a></div>" +
	"		<div id='modalbody'>" +
	"		</div>" +
	"	</div>" +
	"</div>"
	);
};

function removeModalWindow(){
	$('#modalwindow').remove();
};

var modalOnOpen=function(hash){ 
	hash.w.css('opacity',1).show(); 
	
	windowLocation = $(window).scrollTop();
	
	$('html,body').animate({
		scrollTop: 0
	}, 500);
	
	var targetid = String(hash.t).split('#')[1];
	var xmlpath = $('[href=#' + targetid+']').attr('rel').split(",")[0];
	entries = new Array();
	
	$.ajax({
        type: "GET",
		url: xmlpath,
		dataType: "xml",
		success: function(xml) {
			updateModal(xml)
		},
		404: function() {
			console.log('ajax get xml :: 404 ::');
		},
		error: function(jqXHR, textStatus, errorThrown) {
			console.log('ajax get xml :: fail :: ' + textStatus );
		}
	});
}; 

//called from ajax success - parsed xml is used to update the modal window with new images for jcarousel and copy/details/title
var updateModal=function(xml){ 
	//create an array of images
	
	$(xml).find('screens').find('item').each(function(){
		var path = new String();
		path = $(this).text();
		var hrefstring = $(this).attr('href')
		var obj = new Object({ src: path, dom: '<li><img src="' + path + '" width="860" height="500" alt="' + path + '" /></li>', href: hrefstring });
		entries.push( obj );
	});
		
	//add main title
	$('#modalmaintitle').empty();
	$('#modalmaintitle').append($(xml).find('title').text());
	
	//add details
	$('#modalbody').empty();
	$(xml).find('bodyhtml').each(function(){
		var bod = new String();
		bod = $(this).text();
		
		
		$('#modalbody').append(bod);
	});
	
	if( $(xml).find('screens').find('item').attr('href') != "" ) {
		$('#launchsite').find('a').attr('href', $(xml).find('screens').find('item').attr('href') );
		$('#launchsite').show();
	} else {
		$('#launchsite').hide();
	}
	
	$('#collection p').empty();
	$('#collection p').append('1 of ' +entries.length );
	
	//clear carousel and add new images
	addCampaignCarousel();
	modalcarousel.reset();
	currSlide = 1;
	
	$.each(entries, function(index, value) { 
		modalcarousel.add(index, entries[index].dom);
	});
	
	//udpate naviagtion
	checkActives();
}

function updateCollectionNumber(carouselitem, listobj, index, state) {
	$('#collection p').empty();
	$('#collection p').append(index+ ' of ' +entries.length );
	
	if( entries[index-1].href == undefined || entries[index-1].href == "" ) {
		$('#launchsite').css('visibility', 'hidden');
		$('#collection').css('right', '0px');
	} else {
		$('#collection').css('right', '140px');
		$('#launchsite').css('visibility', 'visible');
		$('#launchsite').find('a').attr('href', entries[index-1].href );
	}
}

//used to empty the carousel
var modalOnClose=function(hash){ 
	hash.w.fadeOut(0,function(){ hash.o.remove(); });
	$('#campaigncarousel').empty();
	
	$('html,body').animate({
		scrollTop: windowLocation
	}, 500);
};

function addCampaignCarousel() {
	$('#campaigncarousel').jcarousel({
		wrap: 'circular',
		scroll: 1,
		initCallback: modalcarousel_initCallback,
		buttonNextHTML: null,
		buttonPrevHTML: null,
		itemFirstOutCallback: {
			onBeforeAnimation: checkActives,
			onAfterAnimation: checkActives
		},
		itemVisibleInCallback: {
			onAfterAnimation: updateCollectionNumber
		}
		
	});
	
	$('#mycarousel-next').bind('click', function() {
		var active = getCurrentCarouselItem();
		var activesrc = $(active).children().last().attr('alt');
		
		if( activesrc.trim() == String(entries[entries.length - 1].src).trim() ) {
			return false;
		}
		
		modalcarousel.next();
		return false;
	});
	
	$('#mycarousel-prev').bind('click', function() {
		var active = getCurrentCarouselItem();
		var activesrc = $(active).children().first().attr('alt');
		
		if( activesrc.trim() == String(entries[0].src).trim() ) {
			return false;
		}

		modalcarousel.prev();
		return false;
	});
	
	for(var i in document.links) {
		document.links[i].onfocus = document.links[i].blur;
		document.links[i].hideFocus = true;       // internet explorer
	}
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

//called when modal is opened, and when next/previous is clicked
//used to determine if any should change view to disabled
function checkActives() {
	var active = getCurrentCarouselItem();
	
	var firstactivesrc = $(active).children().first().attr('alt');
	var lastactivesrc = $(active).children().last().attr('alt');
	
	if( firstactivesrc.trim() == String(entries[0].src).trim() ) {
		$("#mycarousel-prev").addClass('deactive');
	} else {
		$("#mycarousel-prev").removeClass('deactive');
	}
	
	if( lastactivesrc.trim() == String(entries[entries.length - 1].src).trim() ) {
		$("#mycarousel-next").addClass('deactive');
	} else {
		$("#mycarousel-next").removeClass('deactive');
	};
	
};

function getCurrentCarouselItem(){
	var currSlide = null;
	$("#campaigncarousel li").each(function(){
		if ($(this).offset().left >= 0){
			currSlide = $(this);
			return false;
		}
	});
	return currSlide;
}

function SetUpNavDrops() {
	var nav = $("nav");
	nav.find("li").each(function() {
		if ($(this).find("ul").length > 0) {
			$(this).find("ul").stop(true, true).slideUp(0);
			//show
			$(this).mouseenter(function() {
				$(this).find("ul").stop(true, true).slideDown();
				CheckMasterNav();
			});				
			//hide
			$(this).mouseleave(function() {
				$(this).find("ul").stop(true, true).slideUp(0);
				CheckMasterNav();
			});
			//click
			//$(this).click(function(){ })
		}
	});
}

//update active states on main nav
function CheckMasterNav() {
	var nav = $("nav");
	nav.find("li").each(function() {
		if ($(this).find("ul").length > 0) {
			//check if any are current page
			$(this).find("li a").each(function(index, element){
				$(element).removeClass('active');
				if( element.href == $.address.baseURL() + window.location.hash ) {
					$(element).addClass('active');
				}
			})
		};
	});
}

function addBubbleScrollHiding() {
	$(window).scroll(function() {
		jQuery.each($('div.speechbubble'), function(){
			$(this).HideBubblePopup();
			if( $(this).hasClass("activebubble") ) {
				$(this).removeClass("activebubble");
			} 
		})
	});
}

function CustomByCaseScenario() {
	$('#clients').show(); //make sure if there is a clients panel to show. If deeplink = clients we hide it.
	
	var htmldoc = new String();
	var tot = new Array();
	tot = String(window.location).split('/');
	htmldoc = tot[tot.length - 1];
	
	switch(htmldoc)
	{
	case 'product_suite.html':
		createBubbles();
	break;
	case 'about_team.html':
	  	createBubbles();
		
		$('.teamblock').each(function(index) {
   			$(this).prepend('<div class="hovereffect"></div>');
		});
  
		
	break;
	case 'product_demand.html':
	  	jQuery('#quotecarousel').jcarousel({
			wrap: 'circular',
			animation: 'slow',
			auto: 7,
			scroll: 1,
			buttonNextHTML: null,
			buttonPrevHTML: null
		});
	break;
	case 'demand_multitouch.html':
		createQuoteCarousel()
	break;
	case 'demand_webinar.html':
		createQuoteCarousel()
	break;
	case 'demand_events.html':
		createQuoteCarousel()
	break;
	case 'about_clients.html':
		$('#clients').hide();
	break;
	default:
	}
}

function createQuoteCarousel() {
	jQuery('#quotecarousel').jcarousel({
		wrap: 'circular',
		animation: 'slow',
		scroll: 1,
		buttonNextHTML: null,
		buttonPrevHTML: null
	});	
}

function createBubbles() {
	$('div.speechbubble').CreateBubblePopup();
	//this needs to change...
	positions = {
		'team00'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team01'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team02'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team03'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team04'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team05'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team06'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team07'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team08'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team09'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team10'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team11'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team12'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team13'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team14'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team15'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team16'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team17'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team18'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team19'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team20'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team21'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team22'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team23'		: {position: 'top',    align: 'left', theme: 'allwhite'   },
		'team24'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team25'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team26'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team27'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team28'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team29'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team30'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team31'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team32'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team33'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team34'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'team35'		: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'team402005031'	: {position: 'top',    align: 'right', theme: 'allwhite'   },
		'e_leads'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'e_pipe'		: {position: 'top',    align: 'middle', theme: 'allwhite'   },
		'e_report'		: {position: 'top',    align: 'middle', theme: 'allwhite'   }
	};
	for(var id in positions){
		var innerHtmlString =  "<div class='bubbleclose' id='_"+ id +"'></div>" + $('#'+id).find('.bdesc').html()
		 
		$('#'+id).SetBubblePopupOptions({
			alwaysVisible: true,
			position : positions[id].position,
			align	 : positions[id].align,
			tail	 : {align: positions[id].align},
			distance: '0px',
			dropShadow: false,
			selectable: true,
			openingDelay: 0,
			openingSpeed: 1,
			closingDelay: 0,
			closingSpeed: 1,
			innerHtml: innerHtmlString,
			mouseOut: 'hide',
			mouseOver: 'hide',
			themeName: 	positions[id].theme,
			themePath: 	'img/bubblepopup',
			afterShown: function() {
				jQuery.each($('div.speechbubble'), function(){
					if( $(this).hasClass("activebubble") ) {
						$(this).FreezeBubblePopup()
					} else {
						$(this).UnfreezeBubblePopup()
					}
				})
			},
			afterHidden: function() {}						
		}); 
	}; //end loop
		
		$('div.speechbubble').bind('mouseover', function(event){
	});
	
	$('div.speechbubble').bind('click', function(event){
		event.preventDefault();
		jQuery.each($('div.speechbubble'), function(){
			$(this).HideBubblePopup()
			if( $(this).hasClass("activebubble") ) {
				$(this).removeClass("activebubble");
			} 
			
		})
			
		var activeitem = $('#'+this.id);
		activeitem.UnfreezeAllBubblePopups();
		activeitem.ShowBubblePopup();
		activeitem.addClass("activebubble");
		activeitem.FreezeAllBubblePopups();
		
		$('.bubbleclose').bind('click', function(event){
			jQuery.each($('div.speechbubble'), function(){
			$(this).HideBubblePopup()
			if( $(this).hasClass("activebubble") ) {
				$(this).removeClass("activebubble");
			} 
			
			})
		});
	})
		
	$(window).resize(function(){
		$('div.speechbubble').HideAllBubblePopups();
		$('div.speechbubble').removeClass("activebubble");
	})
	
	addBubbleScrollHiding()
	
	$('div.speechbubble').each(function(index) {
		if( $(this).hasClass("hiddenbubble")) {
		$(this).unbind('click');
	}
	});
	
}

function removeAnyBubbles() {
	if ( $('div.speechbubble').length > 0 ) {
		$('div.speechbubble').RemoveBubblePopup();
	}
}

function SetUpCampaignFiltering() {
	$('#c_filter li').bind('click', function(event) {
		event.preventDefault();
		
		$('#c_filter li').each( function(index) {
			if( $(this).hasClass('active') ) {
				$(this).removeClass('active');
			}
		});
		
		$(this).addClass('active');
		activeFilter = $(this).find('a').attr('href');
		
		updateFilter();
	});
}

//filtering on the soultions page
function updateFilter() {
	$('.c_entry').each(function(index){
		var myfilters = new Array();
		var visibility = new String();
		visibility = 'none';
		
		myfilters = $(this).find('a').attr('rel').split(",")[1].split("|");
		$.each(myfilters, function(index, value) { 
			if( activeFilter == '#all' ) {
				visibility = 'block';
			}
		
			if( '#'+value == activeFilter ) {
				visibility = 'block';
			}
		});
		
		$(this).css({'display':visibility });

	}) 	
}

function clientcarousel_initCallback(carousel)
{
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

function modalcarousel_initCallback(carousel)
{
	modalcarousel = carousel;
};

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1' target='_blank'>$1</a>"); 
}

function updateTwitter() {
	
	$.ajax({
        type: "GET",
		url: 'xml/edtwitterfeed.xml',
		dataType: "xml",
		success: function(xml) {
			$(xml).find('status').each(function(){
				var time = new String();
				time = $(this).find('created_at').first().text();
				var tweet = new String();
				tweet = $(this).find('text').text();
				var tweetobj = new Object({ time: time, tweet: tweet });
				tweetArray.push(tweetobj);
				
				$('#tweetcarousel').append('<li><div class="tweettext"><p>'+replaceURLWithHTMLLinks(tweet)+'</p><cite>'+localTimeFromUTC(time)+'</cite></div></li>');
				
			});
			
			jQuery('#tweetcarousel').jcarousel({
				wrap: 'circular',
				animation: 'slow',
				auto: 7,
				scroll: 1,
				buttonNextHTML: null,
				buttonPrevHTML: null
			});
			
		},
		404: function() {
			console.log('ajax get xml :: 404 ::');
		},
		error: function(jqXHR, textStatus, errorThrown) {
			console.log('ajax get xml :: fail :: ' + textStatus );
		}
	});
}

function localTimeFromUTC(format) { 
	var reformat = new String()
	var arr = new Array()
	arr = format.split(' ')	
	var timeArr = new Array()
	timeArr = arr[3].split(':')
	var time = new String()
	var ampm = new String()
	ampm = timeArr[0]
	if ( ampm > 12 ) {
		time = 	(timeArr[0] - 12)+":"+timeArr[1]+"pm"
	} else {
		time = 	(timeArr[0])+":"+timeArr[1]+"am"
		if( time.charAt(0) == 0 ) {
			time = time.substring(1, time.length)
		}
	}
	reformat = time + " " + arr[1] + " " + arr[2] + ", " + arr[5]
	//return localDateString
	return reformat
}; 


