$(document).ready(function() {
	if ($(".fbConnectWidgetTopmost"))  {
		$(".fbConnectWidgetTopmost").css({ 'border': 'none'});
	}

  if ($(".special-offer")) {
    $(".special-offer").delay(1500).animate({opacity: 1.0});
  }
  
  if ($.browser.msie) {    
    var has_flash;    
    try {
      has_flash = !! navigator.plugins['Shockwave Flash'] || !! (new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
    } catch (e) {
      has_flash = false;
    }
    
    if (has_flash) {
      $("a.colorbox-video").colorbox({iframe:true, innerWidth:600, innerHeight:338});
    } else {      
      $("a.colorbox-video").attr({'href': '#flash_required' }).after('<div style="display: none;"><p id="flash_required" style="text-align: center;font-size: 16px;margin-top: 150px;"><strong>Flash player is required to view this video. <a href="http://get.adobe.com/flashplayer/" target="_blank">Get it here</a></strong></p></div>');            
      $("a.colorbox-video").colorbox({inline:true, innerWidth:600, innerHeight:338, href:"#flash_required"});
    }
  } else {
    $("a.colorbox-video").colorbox({iframe:true, innerWidth:600, innerHeight:338});                          
  }  
  
  
  $("a.colorbox-photo").colorbox();
  $("a.colorbox-inline").colorbox({width:"585px", inline:true, href:"#watch_demo_form"});
  $("a.colorbox-inline-modal").colorbox({width:"585px", inline:true, href:".modal_form"});  
  
  if ($("a.colorbox-photo.with_icon").length > 0) {
    $("<div class='watermark'></div>").insertBefore("a.colorbox-photo img");
  }
  
  if ($("a.colorbox-video.with_icon").length > 0) {
    $("<div class='watermark'></div>").insertBefore("a.colorbox-video img");
  }

  $("a.boxy").boxy({closeText: null});
  
  $(document).ready(function(){	
    $("#provider-slider").easySlider({
      auto: true, 
      continuous: true,
      numeric: false,
      pause: 3500,
      controlsShow: true,
      doubleControls: false
    });
  });	

/*
  Disabling headline animation for now - it might come back at a later date...
  
	if ($(".headlines")) {
		var numHeadlines = $(".headlines").children(".headline").length;
		var rand = Math.floor(Math.random() * numHeadlines);
		
		var headline = $($(".headlines").children(".headline")[rand]);
		$(headline).css("display", "block");
		
		var header1 = $(headline).children()[0];
		var header2 = $(headline).children()[1];
		var tagline = $(headline).children()[2];

			$(header1).delay(1200).animate({color: "#33302E"}, 1000, function() {
				$(header2).delay(1000).animate({color: "#33302E"}, 1000, function() {
					$(header2).delay(3000).animate({color: "#33302E"}, 1000, function() {
						if (tagline) {
							$(header1).animate({
								color: "#ffffff"
							}, {
								queue: false,
								duration: 100
							}).animate({
								top: '-=75'
							}, 500);
							$(header2).animate({
								color: "#ffffff"
							}, {
								queue: false,
								duration: 100
							}).animate({
								top: '-=75'
							}, 500);
							$(tagline).animate({
								color: "#33302E"
							}, {
								queue: false,
								duration: 2000
							}).animate({
								top: '5px'
							}, 500);
						}	
					});
				});
			});
	}
  */
  	

	if ($("#accordian")) {
	    $("#accordion").accordion({ autoHeight: false });
	}

  if ($("textarea.Comments")) {
    //$("textarea.Comments").bind("change keyup", function() { updateContactCountdown() });
    $("textarea.Comments").bind("change keyup", function() { limitTextareaChars() });
  }      

	
	var url = 'http://api.twitter.com/1/favorites/doxo.json?include_rts=true&include_entities=true&callback=twitterCallback2&count=1';

  	var script = document.createElement('script');
  	script.setAttribute('src', url);
  	document.body.appendChild(script);

  $("a[data-tracking]").live("click", function() {
    var $self = $(this);
    try{
      // make sure we have all of the attributes that we need to send a fully-formed tracking event
      if(!$self.attr("rel")) {
        throw new Error("tracking links must have a rel attribute");
      }
      // send the tracking event
      _gaq.push(["_trackEvent", $self.attr("rel"), $self.attr("data-tracking"), document.location.href]);
    }
    catch(err) {
      // swallow analytics-specific errors, since that's not really our issue here
      error = err + ""; // convert the error to a string
      if(!error.match(/_gaq/)) {
        alert(error);
      }
    }
  });

  jQuery.validator.addMethod("generalUSPhone", function( phone_number, element ){
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(\+)?(1-?)?(\([0-9]\d{0,2}\)\s?|[0-9]\d{2})[-|\s]?[0-9]\d{2}[-|\s]?\d{4}$/);
  }, "Please specify a valid phone number (such as 111-222-3333");

});

function clearField(element, val) {
	if (element.value == val) {
		element.value = "";
		$(element).css("color", "#585351");
	}
}

function setField(element, val) {
	if ((element.value == null) || (element.value == "")) {
		element.value = val;
		$(element).css("color", "#a7a5a4");
	}
}

function clearMsg(msg) {
	$("#formSuccessMsg").css("display","none");
}

/*function updateContactCountdown() {
    var remaining = 250 - $('textarea.Comments').val().length;
    $('p.countdownMsg').text('Be brief. ' + remaining + ' characters remaining.');
    if (remaining < 0) {
      $('p.countdownMsg').addClass('warning');      
    }
		else {
			$('p.countdownMsg').removeClass('warning');
		}
}*/

function limitTextareaChars()
{
	var text = $('textarea.Comments').val();	
	var textlength = text.length;
	var remaining = 250 - textlength;
	$('p.countdownMsg').text('Be brief. ' + remaining + ' characters remaining.');
	
	if(textlength > 250)
	{
		$('p.countdownMsg').addClass('warning');
		$('p.countdownMsg').text('Please limit comments to 250 characters.');
		$('textarea.Comments').val(text.substr(0,250));
		return false;
	}
	else
	{
		$('p.countdownMsg').text('Be brief. ' + remaining + ' characters remaining.');
		return true;
	}
}

function roundImage() {

/*	
	$('.round img').each (
	
		function (intIndex) {

			$(this).wrap('<div class="img_box" />');
			
			$(this).parent('.img_box').css('width', $(this).find('img').css('width'));
			$(this).parent('.img_box').css('height', $(this).find('img').css('height'));
					
			if ($(this).hasClass('alignright')) {
				$(this).parent('.img_box').addClass('alignright');
			}
			
			if ($(this).hasClass('alignleft')) {
				$(this).parent('.img_box').addClass('alignleft');
			}
		
			$(document).ready(function(){
				$(this).parent('.img_box').corner("5px");
			});
			
		}
	
	);
	
*/
}

function twitterCallback2(twitters){
	if ($('#twitter_update_list')) {
		var statusHTML = [];
		for (var i = 0; i < twitters.length; i++) {
			var username = twitters[i].user.screen_name;
			var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url){
				return '<a href="' + url + '">' + url + '</a>';
			}).replace(/\B@([_a-z0-9]+)/ig, function(reply){
				return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
			});
			statusHTML.push('<li><a href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + ' by ' + username + '</a><span>' + status + '</span></li>');
		}
		$('#twitter_update_list').html(statusHTML.join(''));
	}
}

function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);

	if (delta < 60) {
		return 'less than a minute ago';
	} else if(delta < 120) {
		return 'about a minute ago';
	} else if(delta < (60*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (120*60)) {
		return 'about an hour ago';
	} else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return (parseInt(delta / 86400)).toString() + ' days ago';
	}
}

$('.requestModal').live('click', function(e) {
  e.preventDefault();
  console.log('requestModal');
  Boxy.load('/request-invite', {
    behaviours: function(r) {
      r.find("#inviteFormModal").validate({
        errorClass: "fieldWithErrors",
        validClass: "valid",
        highlight: function(element, errorClass, validClass) {
          $(element).parent("div").addClass(errorClass);
        },
        unhighlight: function(element, errorClass, validClass) {
          $(element).parent("div").removeClass(errorClass);
        },
        submitHandler: function(form) {
          r.find('#formErrorMsg').hide();
          form.submit();
        },
        invalidHandler: function(form, validator) {
          r.find('#formErrorMsg').show();
        }
      });
    }
  });
});

$("a[data-sign-up]").live("click", function(e) {
  e.preventDefault();
  $(this).closest("form").submit();
});

$(function(){ 
  if ($.browser.msie) {    
    var has_flash;
    
    try {
      has_flash = !! navigator.plugins['Shockwave Flash'] || !! (new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
    } catch (e) {
      has_flash = false;
    }
    
    if (has_flash) {
      $("a[rel=\"video\"]").colorbox({iframe: true, innerHeight: 338, innerWidth: 600, rel: 'nofollow'});
    } else {      
      $("a[rel=\"video\"]").attr({'href': '#flash_required' }).after('<div style="display: none;"><p id="flash_required" style="text-align: center;font-size: 16px;margin-top: 150px;"><strong>Flash player is required to view this video. <a href="http://get.adobe.com/flashplayer/" target="_blank">Get it here</a></strong></p></div>');                  
      $("a[rel=\"video\"]").colorbox({inline:true, innerWidth:600, innerHeight:338, href:"#flash_required"});      
      
      $('#demo_video iframe').hide();
      $('#flash_required').show();
      
    }

  } else {
    $("a[rel=\"video\"]").colorbox({iframe: true, innerHeight: 338, innerWidth: 600, rel: 'nofollow'});                             
  }  
  
});

