jQuery(document).ready(function() {
	
	if(jQuery.browser.msie && jQuery.browser.version == 6) {
		jQuery('img[@src$=.png]').each(function(i){
			var x = jQuery(this).attr("src");
			var y = jQuery(this).attr("class");
			var z = jQuery(this).attr("id");
			x = x.substring(0, x.indexOf('.png'));
			jQuery(this).replaceWith('<img src="' + x + '.gif" class="' + y + '" id="' + z + '"/>');
		});
		
		jQuery('#corners-top').remove();
		jQuery('#corners-bottom').remove();
	}

	// replace page background to match section
	var current = jQuery('#nav ul').find('a.current').text().toLowerCase();
	var section = jQuery('#nav ul').find('a.section').text().toLowerCase();
	
	if(current == "publishers" || section == "publishers"){
		jQuery('html').css({'background-image':'url(themes/adify/images/page-bg-blue.png)'});
	} else if(current == "advertisers" || section == "advertisers"){
		jQuery('html').css({'background-image':'url(themes/adify/images/page-bg-ltblue.png)'});
	} else if(current == "network builders" || section == "network builders"){
		jQuery('html').css({'background-image':'url(themes/adify/images/page-bg-green.png)'});
	} else if(current == "solutions" || section == "solutions"){
		jQuery('html').css({'background-image':'url(themes/adify/images/page-bg-gold.png)'});
	} else {
		jQuery('html').css({'background-image':'url(themes/adify/images/page-bg-orange.png)'});
	}
	jQuery('html:has(div#logo-scroll)').css({'background-image':'url(themes/adify/images/page-bg-home.png)'});


	if(jQuery.browser.msie && jQuery.browser.version == 6){
		// do nothing
	} else {
		// pull Headline from man nav and search for replacement image
		var name;
		var img;
		var title = jQuery('#headline h1 b').text();

		if(title!="Welcome to Adify") {
			jQuery('#nav ul li').each(function(i){
				if(jQuery(this).children('a').hasClass('current') || jQuery(this).children('a').hasClass('section')){
					name = jQuery(this).text().replace(/\s+/g, '').toLowerCase();
					img = "themes/adify/images/title-"+name+".png";
				} else {
					title = title.replace(/\s+/g, '').toLowerCase();
					img = "themes/adify/images/title-"+title+".png";
				}
			});
			
			if(isFile(img)){
				var style = "transparent url("+img+") left center no-repeat"
				jQuery('#headline h1').css({'background':style}).children('b').css({'display':'none'});
			} else {
				img = "themes/adify/images/title-adify.png";
				var style = "transparent url("+img+") left center no-repeat"
				jQuery('#headline h1').css({'background':style}).children('b').css({'display':'none'});
			}
		}
	}

	// These are the functions to see if the file exists on the server.
	function isFile(str){
		var O = AJ();
		if(!O) return false;
		try{
			O.open("HEAD", str, false);
			O.send(null);
			return (O.status==200) ? true : false;
		} catch(er) {
			return false;
		}
	}
	function AJ(){
		var obj;
		if (window.XMLHttpRequest){
			obj= new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			try{
				obj= new ActiveXObject('MSXML2.XMLHTTP.3.0');
			} catch(er) {
				obj=false;
			}
		}
		return obj;
	}


	// homepage carousel
	var carousel_itemList = [];
	
	function carousel_itemVisibleInCallback(carousel, item, i, state, evt){
		var idx = carousel.index(i, carousel_itemList.length);
		carousel.add(i, carousel_getItemHTML(carousel_itemList[idx - 1]));
	};
	
	function carousel_itemVisibleOutCallback(carousel, item, i, state, evt){
		carousel.remove(i);
	};
	
	function carousel_getItemHTML(item){
		return '<img src="' + item + '"/>';
	};
	
	jQuery('#logo-scroll ul li').each(function(i){
		var currentSrc = jQuery(this).children('img').attr('src');
		jQuery(this).remove();
		carousel_itemList.push(currentSrc);
	});
	
	// IE6 functionality split
	if(jQuery.browser.msie && jQuery.browser.version == 6){
		
		// creates an Array Randomizer function
		function randOrd(){
			return (Math.round(Math.random())-0.5);
		} 
		
		// randomize the array
		carousel_itemList.sort(randOrd);
		
		// write the array to the page
		for ( i=0; i < carousel_itemList.length; i++ ){
			var currentSrc = carousel_itemList[i]
			jQuery('#logo-scroll ul').append('<li><img src="'+currentSrc+'"/></li>');
		}
		
		// style and positioning
		jQuery('#logo-scroll ul').css({'padding':'0px','margin':'0px','width':'654px','list-style':'none','position':'relative','left':'-3px'});
		jQuery('#logo-scroll ul').prev().css({'position':'relative','left':'-6px'});
		jQuery('#logo-scroll ul li').slice(4).remove()
		jQuery('#logo-scroll ul li').css({'float':'left','height':'75px','display':'inline','margin':'0px 18px 0px 18px'});
		
		// vertically centering
		jQuery('#logo-scroll ul li').each(function(i){
			var newHeight = jQuery(this).children('img').height();
			newHeight = (newHeight/2)*-1;
			jQuery(this).children('img').css({'position':'relative','top':'50%','margin-top':newHeight});
		});
	} else {
		// carousel trigger
		var scrollNum = jQuery('#logo-scroll ul li').size()
		jQuery('#logo-scroll ul').jcarousel({
			animation: 10000,
			auto: .001,
			wrap: 'circular',
			scroll: 4,
			itemVisibleInCallback: {onBeforeAnimation: carousel_itemVisibleInCallback},
			itemVisibleOutCallback: {onAfterAnimation: carousel_itemVisibleOutCallback}
		});
	}

	// Home Page Buckets - Bold the last word in the title
	jQuery('#home div[id*="bucket"] h2').each(function(i){
		var str = jQuery(this).text();
		var start = str.lastIndexOf(" ");
		var everythingElse = str.substring(0, start);
		var lastWord = str.substring(start, str.length);
		var extraStuff = jQuery(this).find('a').outerHTML();
		jQuery(this).html(everythingElse + " <b>" + lastWord + "</b>" + extraStuff);
	});

	jQuery.fn.outerHTML = function(s) {
		return (s)
		? this.before(s).remove()
		: jQuery("<p>").append(this.eq(0).clone()).html();
	}



	// Management Team Expand/Contract
		// on-page-load
	var str,len,start,end
	jQuery('#team .module').each(function(i){
		var modHeight = jQuery(this).height();
		jQuery(this).attr({id:modHeight});
		jQuery(this).css({'height':'64px','background':'#e1e0e9 url(themes/adify/images/expand-closed-bg.png) 0px 0px repeat-x'});
		jQuery(this).children('div#left').css({'width':'55px'}).children('img').css({'width':'44px','height':'60px'});
		jQuery(this).children('div#right').children('h3').addClass('closed').children('a').css({'color':'#77777f'});
		jQuery(this).children('div#right').children('h4').css({'margin':'0px','border':'none','padding':'0px'});
		jQuery(this).children('div#right').children('p').css({'display':'none'});
		jQuery(this).children('div#right').children('p:first').css({'display':'block'});
			str = jQuery(this).children('div#right').children('p:first').text();
			len = 75;
			if (str.length > len) {
				start = str.substring(0, len).replace(/\w+$/, '');
				end = str.substring(start.length, str.length);
				jQuery(this).children('div#right').children('p:first').html(start + "<em>...</em><span style='display:none;'>" + end + "</span>");
			}
		jQuery(this).children('div#right').children('span').css({'display':'none'});
		jQuery(this).children('span.arrow').addClass('closed').children('a').css({'background-position':'0px 0px'});
	});

		// on click expand
	jQuery('#team .module').click(function(){
		if(jQuery(this).children('div#right').children('h3').hasClass('open')){
			jQuery(this).animate({'height':'64px'}).css({'background':'#e1e0e9 url(themes/adify/images/expand-closed-bg.png) 0px 0px repeat-x'});
			jQuery(this).children('div#left').animate({'width':'55px'}).children('img').animate({'width':'44px','height':'60px'});
			jQuery(this).children('div#right').children('h3').removeClass('open').addClass('closed').children('a').css({'color':'#77777f'});
			jQuery(this).children('div#right').children('h4').css({'margin':'0px','border':'none','padding':'0px'});
			jQuery(this).children('div#right').children('p').css({'display':'none'});
			jQuery(this).children('div#right').children('p:first').css({'display':'block'});
			jQuery(this).children('div#right').children('p').children('em').css({'display':'inline'}).next().fadeOut();
			jQuery(this).children('div#right').children('span').css({'display':'none'});
			jQuery(this).children('span.arrow').removeClass('open').addClass('closed').children('a').css({'background-position':'0px 0px'});
			return false;
		} else {
			var modHeight = jQuery(this).attr('id') + "px";
			jQuery(this).css({'background':'none'}).animate({'height':modHeight});
			jQuery(this).children('div#left').animate({'width':'87px'}).children('img').animate({'width':'76px','height':'103px'});
			jQuery(this).children('div#right').children('h3').removeClass('closed').addClass('open').children('a').css({'color':'#77777f'});
			jQuery(this).children('div#right').children('h4').css({'margin':'0px 0px 10px 0px','border-bottom':'1px solid #e1e0e9','padding':'0px 0px 10px 0px'});
			jQuery(this).children('div#right').children('p').css({'display':'block'}).children('em').css({'display':'none'}).next().fadeIn();
			jQuery(this).children('div#right').children('span').css({'display':'block'});
			jQuery(this).children('span.arrow').removeClass('closed').addClass('open').children('a').css({'background-position':'0px -15px'});
			return false;
		}
	});
	
	jQuery('#team .module').hover(function(){
	   jQuery(this).children('#right').children('h3.closed').children('a').css({'color':'#fe9416'});
	   jQuery(this).children('#left').children('img').css({'border-color':'#fe9416'});
	}, function(){
	   jQuery(this).children('#right').children('h3.closed').children('a').css({'color':'#77777f'});
	   jQuery(this).children('#left').children('img').css({'border-color':'#8d8d96'});
	});
	

	// Careers Expand/Contract
		// on-page-load
	jQuery('.jobs .module').each(function(i){
		var modHeight = jQuery(this).height();
		jQuery(this).attr({id:modHeight});
		jQuery(this).children('*').slice(3).css({'display':'none'});
		jQuery(this).children('p').css({'margin':'0px 0px 0px 0px'});
		jQuery(this).append('<span><a href="#" class="more">View Details</a></span>');
		if(jQuery.browser.msie && jQuery.browser.version == 6){
			//do nothing
		} else {
			jQuery(this).css({'background':'#e4e1e0 url(themes/adify/images/expand-closed-bg.png) 0px 0px repeat-x'});
		}
		jQuery(this).children('h3').addClass('closed');
		jQuery(this).children('span.arrow').addClass('closed').children('a').css({'background-position':'0px 0px'});
		var collapseHeight = jQuery(this).height();
		jQuery(this).attr({alt:collapseHeight});
	});

		// on click expand
	jQuery('.jobs .module a:not(a#apply)').click(function(){
		var container = jQuery(this).parent().parent();
		var modHeight = container.attr('id');
		var collapseHeight = container.attr('alt');
		if(container.children('h3').hasClass('open')){
			container.animate({'height':collapseHeight+"px"});
			if(jQuery.browser.msie && jQuery.browser.version == 6){
				// do nothing
			} else {
				container.css({'background':'#e1e0e9 url(themes/adify/images/expand-closed-bg.png) 0px 0px repeat-x'});;
			}
			container.children('*').slice(3).fadeOut();
			container.children('h3').removeClass('open').addClass('closed');
			container.children('p').css({'margin':'0px 0px 0px 0px'});
			container.find('span a.more').parent().css({'display':'block'});
			container.children('span.arrow').removeClass('open').addClass('closed').children('a').css({'background-position':'0px 0px'});
			return false;
		} else {
			container.animate({'height':modHeight});
			container.css({'background':'none'});
			container.children('*').slice(2).fadeIn();
			container.children('p').css({'margin':'0px 0px 20px 0px'});
			container.children('span.arrow').removeClass('closed').addClass('open').children('a').css({'background-position':'0px -15px'});
			container.children('h3').removeClass('closed').addClass('open');
			container.find('span a.more').parent().css({'display':'none'});
			return false;
		}
	});
	

	// faux counters for home page stats
	setInterval(function statServed(){
		var servedStr = jQuery('#home #headline #platform #stats p#served').text();
		servedStr = stripNonNumeric(servedStr);
		servedStr = parseFloat(servedStr);
		servedStr = servedStr + 839;
		servedStr = addCommas(servedStr);
		jQuery('#home #headline #platform #stats p#served').text(servedStr);
	}, 1000);

	setInterval(function statSites(){
		var sitesStr = jQuery('#home #headline #platform #stats p#sites').text();
		sitesStr = stripNonNumeric(sitesStr);
		sitesStr = parseFloat(sitesStr);
		sitesStr = sitesStr + 1;
		sitesStr = addCommas(sitesStr);
		jQuery('#home #headline #platform #stats p#sites').text(sitesStr);
	}, 6000);
/*
	setInterval(function statNetworks(){
		var networksStr = jQuery('#home #headline #platform #stats p#networks').text();
		networksStr = stripNonNumeric(networksStr);
		networksStr = parseFloat(networksStr);
		networksStr = networksStr + 1;
		networksStr = addCommas(networksStr);
		jQuery('#home #headline #platform #stats p#networks').text(networksStr);
	}, 4900);
*/
	function addCommas(nStr){
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}

	function stripNonNumeric(str){
		str += '';
		var rgx = /^\d|\.|-$/;
		var out = '';
		for( var i = 0; i < str.length; i++ ){
			if( rgx.test( str.charAt(i) ) ){
				if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
					( str.charAt(i) == '-' && out.length != 0 ) ) ){
					out += str.charAt(i);
				}
			}
		}
		return out;
	}


	// Featured Networks RollOver
	var config = {    
		sensitivity: 25,   
		interval: 50,
		over: bringItIn,
		timeout: 0,
		out: sendItOut 
	};
	
	var numItemsIE7Bug = jQuery('#content #main #featured li').size();
	jQuery('#content #main #featured li').each(function(i){
		jQuery(this).css({'z-index':numItemsIE7Bug});
		numItemsIE7Bug--
	});
	
	if(jQuery.browser.msie && jQuery.browser.version == 6) {
		jQuery('#content #main #featured li').each(function(i){
			var featuredLink = jQuery(this).find('a:has(img)').attr('href');
			jQuery(this).wrap('<a href="'+featuredLink+'"></a>').css({'cursor':'pointer'});
		});
	} else {
		jQuery('#content #main #featured li').hoverIntent(config);
	}

	function bringItIn(){
		jQuery(this).children('div').fadeIn(250).css({'z-index':'1337'});
	}	
	
	function sendItOut(){
		jQuery(this).children('div').fadeOut(250).css({'z-index':'1'});;
	}
/*
	jQuery('#content #main #featured li img:not(img#headshot)').each(function(i){
		var temp = jQuery(this).height();
		temp = (temp/2)*-1;
		jQuery(this).css({'margin-top':temp});
	});
*/	
	// resize featured network profile image
	jQuery('#featured ul li').each(function(i){
		var imgWidth = jQuery(this).children('#popup').children('div').children('.resized-img').children('img').width();
		var imgHeight = jQuery(this).children('#popup').children('div').children('.resized-img').children('img').height();
		
		if(imgWidth > imgHeight){
			imgWidth = (63*imgWidth)/imgHeight;
			imgWidth = Math.round(imgWidth);
			imgHeight = 63;
			jQuery(this).children('#popup').children('div').children('.resized-img').children('img').css({'width':imgWidth,'height':imgHeight});
		} else {
			imgHeight = (63*imgHeight)/imgWidth;
			imgHeight = Math.round(imgHeight);
			imgWidth = 63;
			jQuery(this).children('#popup').children('div').children('.resized-img').children('img').css({'width':imgWidth,'height':imgHeight});
		}

		jQuery(this).children('#popup').css({'visibility':'visible','display':'none'});
	});




	// Various Tweaks and Fixes
	//jQuery('input#SearchForm_SearchForm_action_results').attr({value:' '});

	// Init the slider
	jQuery('div#slider').codaSlider();
	
	// Align the Network-module images in the frames
/*
	jQuery('.network-module ul li.img img').each(function(i){
		var temp = jQuery(this).height();
		temp = (temp/2)*-1;
		var temp2 = jQuery(this).width();
		temp2 = (temp2/2)*-1;
		jQuery(this).css({'margin-top':temp,'margin-left':temp2});
		jQuery(this).css({'margin-left':temp2});
	});
*/

	// Login Modal
	jQuery('a.login').click(function(e) {
		window.location = "https://app.adify.com/SignIn.aspx"
		return false;
	});
	
	// Contact Modal
	jQuery('a.contact-us').click(function(e) {
		jQuery.get('mysite/contact-form.php', function(data){
			jQuery(data).modal({
				onOpen: simplemodal.open,
				onShow: simplemodal.show,
				onClose: simplemodal.close
			});
		});
		return false;
	});
	
	// Live Chat Modal
	jQuery('a.livechat').click(function() {
		scroll(0,0);
		jQuery.get("mysite/livechat.php", function(data){
			jQuery(data).modal({
				onOpen: simplemodal2.open,
				onShow: simplemodal2.show,
				onClose: simplemodal2.close
			});
		});
		return false;
	});
	
var simplemodal = {
	message: null,
	open: function(dialog){
		if(jQuery.browser.msie){
			dialog.overlay.css({'display':'block'});
			dialog.data.css({'display':'block'});
			dialog.container.css({'display':'block'});
		} else {
			dialog.overlay.fadeIn(500, function(){
				jQuery('.modalMiddle').css({'display':'none'}); 
				dialog.data.css({'display':'block'}); 
				dialog.container.fadeIn(250, function(){
					jQuery('.modalMiddle img').css({'display':'none'});
					jQuery('.modalMiddle').slideDown(500,function(){
						jQuery('.modalMiddle img').fadeIn(250);
					});
				});
			});
		}
		// show/hide "state" based on country
		$('select#state').parent('li').hide();
		$('#city').val('n/a').parent('li').hide();
		$('select#country').change(function(){
			if($(this).val() == 'US'){
				$('select#state').parent('li').show();
				$('select#state').find('option:nth-child(1)').text('');
			} else {
				$('select#state').parent('li').hide();
				$('select#state').find('option:nth-child(1)').text('n/a');
			}
		});
		$('select#state').change(function(){
			if($(this).val() == 'CA'){
				$('#city').val('').parent('li').show();
				$('#city').find('option:nth-child(1)').text('');
			} else {
				$('#city').val('n/a').parent('li').hide();
				$('#city').find('option:nth-child(1)').text('n/a');
			}
		});
		// Contact Form Validation
		$('#copyme').validate({
			rules: {
				first_name: {required: true},
				last_name: {required: true},
				email: {required: true, email: true},
				phone: {required: true},
				company: {required: true},
				country:  {required: true},
				state:  {required: true},
				city:  {required: true},
				"00N70000002S0Av": {required: true}
			},
			messages: {
				firstname: "Please enter your first name",
				lastname: "Please enter your las tname",
				email: "Please enter a valid email address",
				phone: "Please enter a valid phone number",
				company: "Please enter a your company",
				country: "Please select a country",
				state: "Please select a state",
				city: "Please select a city",
				"00N70000002S0Av": "Please select an interest"
			}
		});
	},
	close: function(dialog){
		if(jQuery.browser.msie){
			jQuery.modal.close();
		} else {
			jQuery('.modalMiddle img').fadeOut(250);
			jQuery('.modalMiddle').slideUp(500,function(){
				dialog.container.fadeOut(250,function(){
					jQuery.modal.close();
				});
			});
		}
	}
};

var simplemodal2 = {
	message: null,
	open: function(dialog){
		if(jQuery.browser.msie){
			dialog.overlay.css({'display':'block'});
			dialog.data.css({'display':'block'});
			dialog.container.css({'display':'block'});
		} else {
			dialog.overlay.fadeIn(500, function(){
				jQuery('.modalMiddle-sm').css({'display':'none'}); 
				dialog.data.css({'display':'block'}); 
				dialog.container.fadeIn(250, function(){
					jQuery('.modalMiddle-sm img').css({'display':'none'});
					jQuery('.modalMiddle-sm').slideDown(500,function(){
						jQuery('.modalMiddle-sm img').fadeIn(250);
					});
				});
			});
		}
	},
	close: function(dialog){
		if(jQuery.browser.msie){
			jQuery.modal.close();
		} else {
			jQuery('.modalMiddle-sm img').fadeOut(250);
			jQuery('.modalMiddle-sm').slideUp(500,function(){
				dialog.container.fadeOut(250,function(){
					jQuery.modal.close();
				});
			});
		}
	}
};

	// Platform Animations and Interactions
	jQuery('#slides').css({'display':'none','visibility':'visible'});
	
	jQuery('img#launch-platform').click(function(){
		jQuery('#flash').fadeOut();
		jQuery('#text').fadeOut();
		jQuery('#slides').fadeIn();
		return false;
	});
	
	jQuery('a#return').click(function(){
		jQuery('#slides').fadeOut();
		jQuery('#flash').fadeIn();
		jQuery('#text').fadeIn();
		return false;
	});
	
	jQuery('#slides .slide').css({'display':'none'}).filter(':first').css({'display':'block'});
	jQuery('#slides #tabs ul li').filter(':first').addClass('selected').animate({'top':'-10px'},250);
	
	
	jQuery('#slides #tabs ul li').click(function(){
		var target = jQuery('#slides #tabs ul li.selected a').attr('id');
		var hash = jQuery(this).children('a').attr('id');
		if(target == hash){
			return false;
		} else {
			jQuery('#slides #tabs ul li').removeClass('selected');
			jQuery(this).addClass('selected').animate({'top':'-10px'},250);
			jQuery('#slides #tabs ul li:not(.selected)').animate({'top':'0px'},250);
			jQuery('#slides .slide').fadeOut(250);
			jQuery('div[id="'+hash+'"]').fadeIn(250);
			return false;
		}
	});

	// Contact Modal
	jQuery('head').append("<script>function launchy(){jQuery('a.contact-us').click()}</script>");


	// Blog Author Photo Positioning
	if(is_single == false || is_single != true){
		jQuery('#author-photo-holder div').each(function(){
			var currentId = jQuery(this).attr('id');
			currentId = currentId.replace(/\s+/g,'');
			jQuery(this).attr('id',currentId);
		});
		jQuery('p.authorDate').each(function(){
			var currentAuthor = jQuery(this).children('a.author').text();
			currentAuthor = currentAuthor.replace(/\s+/g,'');
			var authorImg = jQuery('#author-photo-holder').find('div#' + currentAuthor + '').html();
			jQuery(this).parent().prepend(authorImg).children('a:first').addClass('post-author-img');
		});
	}

// ---------------------------------------------------------------
// -- Pagination Link --------------------------------------------
// ---------------------------------------------------------------
	jQuery('#main').blogiPagiNav({
    	mainNavSelector: '#subnav',
        subNavSelector: '#subnav > li:has(a.current) + .subsubnav',
		currentClassLocation: 'link',
		prevLink: false,
        homeLink: false,
		location: 'bottom'
	});
	
	jQuery('#subnav > li:has(a.current) ~ .subsubnav');

	// Solutions Sidebar Expand/Collapse
	var nestedSidebar = jQuery('#subnav > ul');
	if(nestedSidebar.length > 0){
		nestedSidebar.each(function(){
			jQuery(this).prev().css({'cursor':'pointer'}).toggle(function () {
				$(this).next().slideDown(250);
			}, function () {
				$(this).next().slideUp(250);
			});
			jQuery(this).css({'display':'none'});
		});
		jQuery('#subnav > li:has(a.current)').next().css({'display':'block'});
	}
	
// -- the end --	
});
