/* Function:    fancy_form_field
 * Description: Hides the labels and adds a listener to clear field value 
 *              onfocus and returns the values onblur if the field is empty.
 * Parameters:  field_id, value
 * Returns:     null
 */
function fancy_form_field (field_id,default_value) {
  $(".hidden").hide();
  $(field_id).val(default_value);
  $(field_id).css('color','#999');
  $(field_id).focus(function(){
    if($(this).val() == default_value) {
      $(this).val('');
      $(this).css('color','#303030')
    }
  }).blur(function(){
    if($(this).val() == '') {
      $(this).val(default_value);
      $(this).css('color','#999')
    }
  })
}

/* Function:    ajax_form
 * Description: binds a FreeForm Form to ajax submit and does all 
 *              work to update the user of an error or to submit.
 * Parameters:  form_id
 * Returns:     null
 */
function ajax_form (form_id) {
  $(form_id).ajaxForm ({              //bind ajax submit to the form
    target:       ".form_response",       //response from submission
    // beforeSubmit: quick_validate, 
    success:      function(response){     //callback function for success  
      if(response == "success"){
        $(form_id).slideUp();
        $('.form_response').html("Your information and message was sent.  We'll be in touch soon.").addClass('success').fadeIn();
        $(form_id).resetForm()      //clear the form
      }else{
        $('.form_response').html($('.form_response #content ul').html()).addClass('error').fadeIn();
      }
    }
  });
}

/* Function:    google_map_ini
 * Description: generates the google map 
 * Parameters:  none
 * Returns:     null
 */
function google_map_ini(lgt, lat, id) {
  var map = new GMap2(document.getElementById(id));
  var location = new GLatLng(lgt, lat);
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  map.setCenter(location, 14);
  map.addOverlay(new GMarker(location));
}

/* Function:    contact_form_ini
 * Description: do some visual tweeking of the contact form 
 *              and make the from submit via XHR 
 * Parameters:  none
 * Returns:     null
 */
function contact_form_ini() {
  // make the form fields act all fancy
  fancy_form_field('#name', 'Name');
  fancy_form_field('#email', 'Email');
  fancy_form_field('#company', 'Company');
  fancy_form_field('#phone', 'Phone');
  fancy_form_field('#message', "Message"); 
  fancy_form_field('#contact_captcha', "Verify Your Humanity"); 

  // ajaxify the form
  ajax_form("#contact_us");
}

/* Function:    flash_builder
 * Description: build the flash and insert it into the  
 *              page to get around IE being dumb and annoying  
 * Parameters:  w,h,bc,id,swf
 * Returns:     null
 */
function flash_builder(w,h,bc,id,swf) {
  var new_html =  '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '
                + '  codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+ w +'" height="'+ h +'">'
                + '  <param name="allowScriptAccess" value="sameDomain" />'
                + '  <param name="quality" value="high" />'
                + '  <param name="allowFullScreen" value="false" />'
                + '  <param name="scale" value="noscale" />'
                + '  <param name="wmode" value="transparent" />'
                + '  <param name="bgcolor" value="'+ bc +'" />'
                + '  <param name="movie" value="/public/flash/'+ swf +'" />'
                + '  <embed src="/public/flash/'+ swf +'"quality="high" bgcolor="'+ bc +'" width="'+ w +'" height="'+ h +'"'
                + 'allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" '
                + 'pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent">'
                + '</embed></object>';

  $(id).html(new_html);		
}

/* Function:    vAlign
 * Description: vertically align a block level element inside another  
 * Parameters:  none
 * Returns:     null
 */
(function ($) {
$.fn.valign = function() {
	return this.each(function(i){
	var ah = $(this).height();
	var ph = $(this).parent().height();
	var mh = (ph - ah) / 2;
	$(this).css('margin-top', mh);
	});
};
})(jQuery);

// Adds onclick events for Google page tracking to all of the dom id's specified in [n][0] of trackableElements
function googlePageTracker(){
	// trackableElements -> 2D array of form ['tracking_id', 'path/for/google']
	var trackableElements = [
		['#btn_contact', '/header/contact-us/'], ['#spell-tocquigny', '/footer/spell-tocquigny/'], ['#privacy-policy', '/footer/privacy-policy/'],
		['a.email-peter-moossy', '/contact-us-form/email-peter-moossy/'], ['a.email-peter-moossy-header', '/contact-us-form/email-peter-moossy/']
	];
	for(x in trackableElements){
		$(trackableElements[x][0]).click(function(){
			pageTracker._trackPageview(trackableElements[x][1]);
		});
	}
}

// Adds onclick events for Google page tracking for all accordion links
function accordionGooglePageTracker(){
	// trackableIds -> 2D array of form ['tracking_id', '/prefix/for/path']
	//   it's assumed that an id wraps a set of the form ul > li > a, then uses the href tag (minus the '#') for the rest of the path for Google
	var ids = [
		['research_and_strategy', '/our-services/'], ['digital_marketing', '/our-services/'], ['advertising_and_branding', '/our-services/'], ['interactive', '/our-services/'],
		['leadership_nav', '/about-us/leadership/']
	];
	for(x in ids){
		$('#' + ids[x][0] + ' > ul > li > a').each(function(){
			$(this).click(function(){
				var path = $(this).attr('href').replace('#', '');
				pageTracker._trackPageview(ids[x][1] + path + '/');
			});
		});
	}
}

//on page load functions
$(document).ready(function() {

  /* build the flash baner
  *****************************************/
  flash_builder("100%","57","#FFFFFF","#banner","banner.swf")

  /* section mainpage accordions
  *****************************************/
  //open the second accordion for services, contact, our-work
  $('#panel_2').each(function(){
    $(this).slideDown('normal',"easeInExpo");
    $(this).prev('h3.accordion_header').children('span.expander').addClass('open');
  })

  //accordion interactions
  $('h3.accordion_header').click(function(){
    //see if the panel is open already
    if ($(this).children('span.expander').hasClass('open')) {
      return; //don't do anything
    }else{
      //close the current panel and open the panel new panel
      $('.accordion_panel').slideUp("slow","easeOutExpo");
      $('span.expander').removeClass('open');
      $(this).children('span.expander').addClass('open');
      $(this).next('.accordion_panel').slideDown("normal","easeInExpo");
    }
  });
  
  $("ul.two_col li:even").css("clear","left");
   
  /* contact us page
  *****************************************/
  //tweek the form
  contact_form_ini()
  
  /* initialize the google map 
   * the first time the panel is opened */
  // $("#google_map_panel").click(function() {google_map_ini(30.266435,-97.742722,"google_map");});
  
  /* contact us panel
  *****************************************/
  $("#btn_contact").click(function(){
    //see if the panel is open
    if ($(".email_form").hasClass("shown")) {
      $(".email_form").slideUp(600,"easeOutExpo").removeClass("shown");
      setTimeout(function() {
          $("#btn_contact").css("background-position","left -67px");
          $("#uber_links li a").css("z-index","1006");
      }, 250);
    }else{
      $(".email_form").slideDown("slow","easeInExpo").addClass("shown");
      $("#uber_links li a").css("z-index","500");
      $(this).css("background-position","left -25px");
    };
  });
  //close button
  $("#btn_contact_close").click(function(){
    if ($(".email_form").hasClass("shown")) {
      $(".email_form").slideUp(600,"easeOutExpo").removeClass("shown");
      setTimeout(function() {
          $("#btn_contact").css("background-position","left -67px");
          $("#uber_links li a").css("z-index","1006");
      }, 250);
    }
    return false;
  });
  

  /* text tweaks
  *****************************************/
  //make the reversed out text have padding on the wrapped lines
  $('span.text_reversed').each(function() {
    $('span.text_reversed br').replaceWith('&nbsp;<br />&nbsp;')
  });
  
  //fix the recent posts on homepage
  // $('ul.recent_posts li').each(function(){
  //   var tag_width = ($(this).children('span.tag').width());
  //   var text_width = (370 - tag_width);
  //   $(this).children('span.tag').width(tag_width + 1);
  //   $(this).children('a').width(text_width);    
  // })

  /* modal windows
  *****************************************/
  $('a.modal_capability, a.modal_video').fancybox({
    'padding': 20,
    'overlayShow': true,
    'autoDimensions': true,
    'autoScale': true,
    'overlayOpacity': 0.75,
    'overlayColor': '#fff',
    'hideOnOverlayClick': true,
    'hideOnContentClick': false,
    'showNavArrows': false,
    'speedIn': 500,
    'titleShow': false
  });
  $('a.modal_text').fancybox({
    'padding': 20,
    'overlayShow': true,
    'autoDimensions': false,
    'autoScale': false,
    'width': 800,
    'height': 'auto',
    'overlayOpacity': 0.75,
    'overlayColor': '#fff',
    'hideOnOverlayClick': true,
    'hideOnContentClick': false,
    'showNavArrows': false,
    'speedIn': 500,
    'titleShow': false
  });
    $('a.modal_text_tight').fancybox({
    'padding': 0,
    'overlayShow': true,
    'autoDimensions': false,
    'autoScale': false,
    'width': 'auto',
    'height': 'auto',
    'overlayOpacity': 0.75,
    'overlayColor': '#fff',
    'hideOnOverlayClick': true,
    'hideOnContentClick': false,
    'showNavArrows': false,
    'speedIn': 500,
    'titleShow': false
  });

  /* tooltips
  *****************************************/
  $(".anchor").tooltip({
    relative: true,
    effect: "slide",
    delay: 100
  });
  //make sure the tooltips are always on top of everything else except modals
  $(".tooltip").css("z-index","1999");
  
});
