window.addEvent('domready', init);
window.addEvent('resize', onResize);

var myVerticalSlide;
var closeDelay;
var myHorizontalSlide;
var slides;
var currPanel;
var big_img_w = 1200;
var big_img_h = 650;

//homepage image start
var scount=1;
//homepage image total
var scountTotal=4;

var myKeyboardEvents;

var homeLinks = new Array('services/bydoctor/', 'articles/a-mobile-campaign-yields-results/','services', 'insights')

function init(){	
	initKeyboard();
	
	doFadeRollovers($$('.fadeover'));
	
	initAccordion();
	initPanelSlide();
	//initHomeSlider();
	initTweets();
	
	initPositions();
	initSubnavSlide();
}




function initKeyboard(){

	myKeyboardEvents = new Keyboard({
    defaultEventType: 'keyup',
    events: {
        'left': scrollMain,
				'right': scrollMain
    }
	});

	myKeyboardEvents.activate();
	//console.log(myKeyboardEvents);

	
	
}

function initPositions(){
	sizeHomeImage();
	posPanel();
}

function onResize(){
	sizeHomeImage();
	posPanel();
}

function sizeHomeImage(){
	var topBarHeight = 2;
	var headerHeight = 82;
	var footerHeight = 36;
	var win_size = window.getSize();
	var win_h = win_size.y - topBarHeight - headerHeight - footerHeight;
	var win_w = win_size.x;
	
	var el = $$('.sizeme');
	if(el!=null){
	
	  	var dest_w = win_w;
			var dest_h = dest_w * (big_img_h / big_img_w);						 
		
		if(dest_h < win_h) {
            // need to scale it back up.
			dest_h = win_h;
     	dest_w = dest_h * (big_img_w / big_img_h);
    }
		
		el.setProperty('width', dest_w);
  	el.setProperty('height', dest_h);
		
		if(dest_w > win_w) {
			el.setStyle('margin-left', Math.floor((dest_w - win_w) / -2));
		} else {
			el.setStyle('margin-left', 0)
		}
		if(dest_h > win_h) {
			el.setStyle('margin-top', Math.floor((dest_h - win_h) / -5));
		} else {
     el.setStyle('margin-top', 0);
		 }
	}
}

function posPanel(){
	var footerPos = $('footer').getPosition();
	var panelSize = $('panelWrapper').getSize();	
	$('panelWrapper').setStyle('top', footerPos.y-panelSize.y);
}

function hideShowPanel(which){
	//console.log(which);
	var size = window.getSize().y;
	var scrol = window.getScrollSize().y;
		
		if(which=='open'){
			$('footer').setStyles({
				position: 'absolute',
				//bottom: '0px'
				top: $('footer').getPosition().y
			});

		}else if(which=='hide'){
			(function(){$('footer').setStyles({
				position: 'relative',
				top: null
			})}).delay(500);

		}
}

function initHomeSlider(){
	
	slides = null;
	slides = $$('.slider-element');	
}

 

function scrollMain(e){
	//console.log(myKeyboardEvents.isActive());
	if(myKeyboardEvents.isActive()){
	myKeyboardEvents.deactivate();
	var whichWay = e.key;
	var dur = 1200;
	var curr_margin_left = $('s'+scount).getStyle('margin-left');
	
	buildSlideshowElements(whichWay);
	
	//console.log(whichWay);
	
	if(whichWay =="left"){
		//console.log('go back')
		$('iconleft').fireEvent('mouseenter');
		$('iconleft').fireEvent('mouseleave', null, 500);
		
		//set morph properties on built elements
	slides[2].set('morph', {duration: dur, transition: Fx.Transitions.Expo.easeIn	});
	slides[1].set('morph', {duration: dur, transition: Fx.Transitions.Expo.easeIn	});
	slides[0].set('morph', {duration: dur, transition: Fx.Transitions.Expo.easeInOut, 
								onComplete:function(){
									//remove hidden elements
									slides[0].getAllNext('.slider-element').dispose();
									myKeyboardEvents.activate();
									
								}	});
	
		slides[2].morph({'marginLeft': 0});
		
		//(function(){slides[2].morph({'marginLeft': 0})}).delay(0);
		(function(){slides[1].morph({'marginLeft': 0})}).delay(200);
		(function(){slides[0].morph({'marginLeft': curr_margin_left})}).delay(650);
		
	}else{
		//console.log('go forward')
		$('iconright').fireEvent('mouseenter');
		$('iconright').fireEvent('mouseleave', null, 500);
		//set morph properties on built elements
	slides[0].set('morph', {duration: dur, transition: Fx.Transitions.Expo.easeIn	});
	slides[1].set('morph', {duration: dur, transition: Fx.Transitions.Expo.easeIn	});
	slides[2].set('morph', {duration: 1700, transition: Fx.Transitions.Expo.easeInOut, 
								onComplete:function(){
									
									//remove hidden elements
									
									slides[3].getAllPrevious('.slider-element').dispose();
									myKeyboardEvents.activate();
								}	});
	
		
		slides[0].morph({'marginLeft': -(slides[0].getSize().x)});
		(function(){slides[1].morph({'marginLeft': -(slides[1].getSize().x)})}).delay(100);
		(function(){slides[2].morph({'marginLeft': -(slides[2].getSize().x)})}).delay(200);
	
	
	}
		
	
	}


}

function buildSlideshowElements(whichWay){

	var spacer1;
	var spacer2;
	
	var nextImage;
	
	//get current image properties
	
	var curr_width = $('s'+scount).getSize().x;
	var curr_height = $('s'+scount).getSize().y;
	var curr_margin_left = $('s'+scount).getStyle('margin-left');
	var curr_margin_top = $('s'+scount).getStyle('margin-top');
	//console.log(curr_width);
	
	if(whichWay =="left"){
		//back
		
		if(scount>1){
			scount--;
		}else{
			scount=scountTotal;
		}
		
		
		
		spacer1 = '<div class="slider-element" id="spacer1" style="margin-left:-400px"></div>';
	 	spacer2 = '<div class="slider-element" id="spacer2" style="margin-left:-400px"></div>';
		nextImage = '<img class="slider-element sizeme" id="s'+scount+'" src="wp-content/themes/cmi/images/home/'+scount+'.jpg" style="margin-left:-'+(curr_width-parseInt(curr_margin_left))+'px"/>';
		
		
		var curr_html = $('slider-list').innerHTML;
		
		$('slider-list').innerHTML = nextImage + 
		spacer2 +
		spacer1 +
		curr_html;
		
		//set properties for next image
		$('s'+scount).setProperty('width', curr_width);
		$('s'+scount).setProperty('height', curr_height);
		//$('s'+scount).setStyle('margin-left', curr_margin_left);
		$('s'+scount).setStyle('margin-top', curr_margin_top);
		$('s'+scount).setProperty('onclick', "location.href='"+homeLinks[scount-1]+"'");
		
		$('spacer1').setStyles({height: curr_height, marginTop:curr_margin_top });
		$('spacer2').setStyles({height: curr_height, marginTop:curr_margin_top });
		
		
	}else{
		//forward
		
		if(scount<scountTotal){
			scount++;
		}else{
			scount=1;
		}
		
		spacer1 = '<div class="slider-element" id="spacer1"></div>';
	 	spacer2 = '<div class="slider-element" id="spacer2"></div>';
		nextImage = '<img class="slider-element sizeme" id="s'+scount+'" src="wp-content/themes/cmi/images/home/'+scount+'.jpg"/>';
		
		$('slider-list').innerHTML = $('slider-list').innerHTML + 
		spacer1 +
		spacer2 +
		nextImage;
		
		//set properties for next image
		$('s'+scount).setProperty('width', curr_width);
		$('s'+scount).setProperty('height', curr_height);
		$('s'+scount).setStyle('margin-left', curr_margin_left);
		$('s'+scount).setStyle('margin-top', curr_margin_top);
		$('s'+scount).setProperty('onclick', "location.href='"+homeLinks[scount-1]+"'");
		
		$('spacer1').setStyles({height: curr_height, marginTop:curr_margin_top });
		$('spacer2').setStyles({height: curr_height, marginTop:curr_margin_top });
	}
	$$('.slideCounter').set('html', '<span>'+scount+'</span> / 4')
	initHomeSlider()
}


function initAccordion(){
	
	
	var fnToRepeat = function() {
	 posPanel();
	};
	var periodicalID;
	
	var myAccordion = new Accordion($('accordion'), 'h3.toggler', 'div.element', {
		opacity: false,
		display: -1,
		alwaysHide: true,

		initialDisplayFx: false,
		onActive: function(toggler, element){
			//toggler.setStyle('color', '#41464D');
		},
		onBackground: function(toggler, element){
			//toggler.setStyle('color', '#528CE0');
		},
		onStart: function(){
			//periodicalID = fnToRepeat.periodical(30);
		},
		onComplete: function(){
			// $clear(periodicalID);
		}
	});
	
	//open the accordion section relative to the url
		
		var found = 0;
		$$('h3.toggler a').each(function(link, i){
			if (window.location.hash.test(link.hash)) found = i;
		});
		
		if (getQueryVariable("place")){
			var which = getQueryVariable("place");
			switch(which){
				case 'king-of-prussia':
					found=0;
					break;
				case 'philadelphia':
					found=1;
					break;
				case 'new-york':
					found=2;
					break;
				case 'pennsauken':
					found=3;
					break;
				
			}
			
		}

		myAccordion.display(found);
		
		//alert( getQueryVariable("place") );

}

function initPanelSlide(){		

$$('div.panelContent').each(function(el) {
			$(el).setStyle('display', 'none');
			
		})
	
	$$('li.button').addEvent('click', function(e) {
		
		$$('li.button').each(function(el) {
			$(el).morph({
        'width': 16
      })											 
		})
		
		$(this).morph({
       // 'margin-top': this.getStyle('margin-top').toInt() == 0 ? 5:0,
				'width': 100
      })
		
		
		var footerPos = $('footer').getPosition();
		var currPanelMargin = $('panel1').getStyle('margin-top').toInt();
		
		var endMargin;
		var endHeight;
		var wrapperHeight;
		
		if(currPanel!=e.target.get('id')){
			endMargin=-113;
			endHeight=113;
			currPanel = e.target.get('id');
			//alert(currPanel);
			wrapperHeight=90;
		}else{
			endMargin=-23;
			endHeight=23;
			currPanel = 0;
			wrapperHeight=0;
		}
		
	/*	$('panel').morph({
      'margin-top': endMargin//90
    })
	*/
	$('panelWrapper').morph({
      'height': endHeight,
			'margin-top': endMargin
    })
		
		$('panelSlider').morph({
      'height': wrapperHeight
    })
		
		$$('div.panelContent').each(function(el) {
			$(el).setStyle('display', 'none');
			
		})
		//alert($('panel'+currPanel));
		if($('panel'+currPanel) != null)
			$('panel'+currPanel).setStyle('display', null);	
		
		
		
	});
	
	
	$$('li.button').addEvent('mouseenter', function(e) {
		
		this.morph({
      'width': 100
    })
																						 
	});
	
		$$('li.button').addEvent('mouseleave', function(e) {
		
		if(currPanel!=e.target.get('id')){
			
			this.morph({'width': 16})
			
		}
		
	
																						 
	});
}


function initSubnavSlide(){
	//opacity
	 $('subnav_wrapper').set('opacity',.9);
	
	//cookie functions disabled, no save state across pages for now
	var togglestate = Cookie.read('togglestate');
	
	myVerticalSlide = new Fx.Slide('subnav_slide', {
		wrapper: $('subnav_wrapper'),
		duration: 400,
		link: 'cancel',
    transition: Fx.Transitions.Quart.easeOut
		//onStart: hideShowPanel

	});
	myVerticalSlide.hide();
	/*if (togglestate == "open"){
	
	myVerticalSlide.show();
		//hideShowPanel('open');
	
		//has the mouse left the header before it loaded?
		document.addEvent('mousemove', function(e){
			//console.log(e.page.y);
			if(e.page.y >200){
				//console.log('mouse is outside header');
				$('header').fireEvent('mouseleave');
			}
		});

		
	}else{
		myVerticalSlide.hide();
	
	}*/
	
	$('header').addEvents({
		'mouseenter': function(){
			//$clear(closeDelay)
			myVerticalSlide.slideIn();
			
			
			//keep footer static
			//hideShowPanel('open');
			
			setCookie('open');
		},
		'mouseleave': function(){
			//console.log('left subnav');
			//myVerticalSlide.slideOut();
			//closeDelay = outDelay.delay(300);
			//outDelay.delay(300);
			
			myVerticalSlide.slideOut();
			//hideShowPanel('hide');
			
			setCookie('close');
			 //
			 	//document.removeEvents('mousemove');
		}
	});
	
	$('subnav_slide').addEvents({
			'mouseleave': function(){
			//myVerticalSlide.slideOut();
			//setCookie('close');

		}
	});												
	
};

function outDelay(){
	//console.log('out');
	myVerticalSlide.slideOut();
	hideShowPanel('hide');
	//console.log('slideout now');
}

function setCookie(which){
	Cookie.write('togglestate', which, {duration: 0});
}

var tweets = new Array();

function initTweets(){

    var twitterRequest = new RequestTwitter({
        parameters: {
            screen_name: 'cmi_media',
            count: 20
        }
    }).addEvents({
        success: function(data) {
            data.each(function(tweet, i) {
								var tweetObj = new Object();
								
								tweetObj.id = tweet.id_str;
								tweetObj.text = tweet.text;
								tweetObj.created_at = tweet.created_at;
								tweetObj.profile_image = tweet.user.profile_image_url;
								tweetObj.username = tweet.user.name
								
								tweets[i] = tweetObj;
								//console.log(tweet)
                /*new Element('div', {
                    html: '<img src="' + tweet.user.profile_image_url.replace("\\", '') + '" align="left" alt="' + tweet.user.name + '" /> <strong>' + tweet.user.name + '</strong><br />' + tweet.text + '<br /><span>' + tweet.created_at + ' via ' + tweet.source.replace("\\", '') + '</span>',
                    'class': 'tweet clear'
                }).inject(twitter);*/

            });
						
						parseTweets();
        }
    }).send();
		
		
}

function parseTweets(){
	
	var profileImagesHtml = '<table cellspacing="0" cellpadding="0" width="100%"><tr>';
	
	
	
	tweets.each(function(tweet, i){
											 
			//profileImagesHtml+='<li class="tweetImage" id="'+i+'"><img src="'+tweets[i].profile_image+'"/></li>';
			profileImagesHtml+='<td valign="bottom" align="center" class="tweetImage" id="'+i+'" height="55"><a href="http://twitter.com/#!/cmi_media/status/'+tweets[i].id+'" target="_blank"><img class="tRollOver" src="'+templateUrl+'/images/twitterProfileImage.jpg"/></a></td>';	
			
			
	
	});
	
	profileImagesHtml += '</tr></table>';
	
	
	$('profileImages').set({html: profileImagesHtml});
	
	$('tweetText').set({html: tweets[0].text});
		$('tweetInfo').set({html: Date.parse(tweets[0].created_at).format('%a %b %e, %Y  %l:%M%p')});
		$('tweetTitle').set({html: tweets[0].username});
	
	initTweetInteraction();
	
}

function initTweetInteraction(){
	$$('td.tweetImage').addEvent('mouseenter', function(e) {
		
		$('tweetText').set({html: tweets[this.id].text});
		$('tweetInfo').set({html: Date.parse(tweets[this.id].created_at).format('%a %b %e, %Y  %l:%M%p')});
		$('tweetTitle').set({html: tweets[this.id].username});
		//this.set({html: '<img src="'+templateUrl+'/images/twitterProfileImageOver.jpg"/>'});
																						 
	});
	
	
	
	
	//rollovers
	$$('img.tRollOver').each(function(img, i) {
		var src;
		if(i==0){
			img.setProperty('src',''+templateUrl+'/images/twitterProfileImageOver.jpg');	
			src = ''+templateUrl+'/images/twitterProfileImage.jpg';
		}else{
			src = img.getProperty('src');
		}
		
		var extension = src.substring(src.lastIndexOf('.'),src.length)
		
		img.addEvent('mouseenter', function() { 
			resetTweetOvers();
			img.setProperty('src',src.replace(extension,'Over' + extension));
			
		});
		
		img.addEvent('mouseleave', function() { 
																				//console.log(img.getParent().id);
			//img.setProperty('src',src);
		});
	});
	
}

function resetTweetOvers(){

	$$('img.tRollOver').each(function(img) {
				img.setProperty('src',''+templateUrl+'/images/twitterProfileImage.jpg');														
	
	});
	
	
}


function initThumbs(who){
	$$('#'+who+'Thumbs img').addEvent('click', function(e) {
		//alert(this.id);	
		
		if(who == 'leadership'){
		var slidesHtml = 
		$(who+'Slideshow').set({html:'<img src="'+templateUrl+'/images/'+who+'/'+this.id+'a.jpg"/><img src="'+templateUrl+'/images/'+who+'/'+this.id+'b.jpg"/><img src="'+templateUrl+'/images/'+who+'/'+this.id+'c.jpg"/><img src="'+templateUrl+'/images/'+who+'/'+this.id+'d.jpg"/>'})
		initLeadershipslides();	
		}else{
			$('content').setStyle('background-image','url('+templateUrl+'/images/'+who+'/'+this.id+'.jpg)');
		}
		
		$$('.'+who+'Info').each(function(i) {
			i.setStyle('display', 'none');
			})
			
			$('t'+this.id).setStyle('display', null);
																	 
	});
	
}



function initLeadershipslides(){
	var slideshow = new SlideShow('leadershipSlideshow', { 
   delay: 4000,
   duration: 1200,
   autoplay: true
  });
}


doFadeRollovers = function(elements) {
	elements.each(function(thisel){
		var src = thisel.getProperty('src');
		src = src.replace('_over','');
		var extension = src.substring(src.lastIndexOf('.'),src.length);
		thisel.getParent().setStyle('background','url('+src.replace(extension,'_over' + extension)+') no-repeat');
		thisel.getParent().setStyle('width',''+thisel.getProperty('width')+'');
		thisel.getParent().setStyle('height',''+thisel.getProperty('height')+'');
		thisel.addEvent('mouseenter', function() { this.fade(0.001); });
		thisel.addEvent('mouseleave', function() {
			this.fade(1);
		});
	});
};



function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  //alert('Query Variable ' + variable + ' not found');
} 






