var assetURL = 'http://www.dfaus.com/managed_dc/'

var vidArray = [];
var vidLength = 0;
var overArrows = false;

$(document).ready(function(){
// setup videos
$('#jVideoDiv').each(function() {
$(this).flash({
swf: assetURL +'swf/playerDC.swf',
allowScriptAccess: 'always',
allowFullScreen: true,
id: 'player',
play: false,
width: 960,
height: 360,
wmode: 'transparent',
flashvars: {
videoXML: assetURL + 'xml/dc.xml'
}
});
});


// video player setup
/*
$('.videoPlayer').each(function() {;
  var thisVideoXml = $(this).find('.videoFile').text()
  $(this).flash({
        swf: 'http://www.dfaus.com/swf/player.swf',
        allowScriptAccess: 'always',
        allowFullScreen: true,
        id: 'player',
        play: false,
        width: '100%',
        height: '100%',
        flashvars: {
        xmlFile: thisVideoXml
      }
    });  
});

*/

// generic hover
$('.jHovImg').hover(function() {
swapImage($(this),'on')
},function() {
swapImage($(this),'off') 
 })

$('.hcDot').hover(function() {
swapImage($(this).not('.hcDotSel'),'on')
$(this).not('.hcDotSel').addClass('hcDotHov')
},function() {
swapImage($(this).not('.hcDotSel'),'off')
$(this).not('.hcDotSel').removeClass('hcDotHov') 
 })

// add all the videos to an array
$('.hvVideo').each(function() {
vidArray.push($(this).attr('id'));  
});
vidLength = vidArray.length;
   
}); //end on ready


// LIVE

// generic stay in hover state
$('.jHovImgStay').live('mouseover',function() {
swapImage($(this),'on')
$(this).siblings('.jHovImgStay').each(function() {
swapImage($(this),'off')
});

 })


var curVid = 0;
// click on left arrow
$('#jhvArrowPrev').live('click', function(e) {
if(curVid==0) {
curVid = vidLength
}
curVid--;
var thisVid = $('.jCurVid');
slide(thisVid, vidArray[curVid], '960px', '-960px', '0px', 'jCurVid');
});

// click on right arrow
$('#jhvArrowNext').live('click', function(e) {
if(curVid==vidLength-1) {
curVid = -1;
}
curVid++;
var thisVid = $('.jCurVid');
slide(thisVid, vidArray[curVid], '-960px', '960px', '0px', 'jCurVid');
});


// animate latest blog items
var curBlog = 0;
$('#jhcArrowPrev').live('click', function(e) {
if(curBlog==0) {
curBlog = $('.hcDot').length
}
curBlog--;
var thisBlog = $('.jCurBlog');
var thisDot = $('#hcDot_'+curBlog)
slideBlog(thisBlog, thisDot,'940px','-940px')
});

// blog right arrow
$('#jhcArrowNext').live('click', function(e) {
if(curBlog==$('.hcDot').length-1) {
curBlog = -1;
}
curBlog++;
var thisBlog = $('.jCurBlog');
var thisDot = $('#hcDot_'+curBlog)
slideBlog(thisBlog, thisDot,'-940px','940px')
});

// click on blog dots
$('.hcDot').live('click', function() {
if(!$(this).hasClass('hcDotSel')) {

var from = '940px';
var to = '-940px';
var thisIndex = $(this).index()

// move left or right
if(curBlog < thisIndex) {
from = '-940px';
to = '940px';
}

curBlog = thisIndex;
var thisBlog = $('.jCurBlog')
slideBlog(thisBlog, $('#hcDot_'+curBlog), from, to);
}
});

// click on next
$('.jHcNext').live('click', function() {
if(curBlog==$('.hcDot').length-1) {
curBlog = -1;
}
curBlog++;
var thisBlog = $('.jCurBlog')
slideBlog(thisBlog, $('#hcDot_'+curBlog), '-940px', '940px');
});

// click on video nav buttons
$('.hvThumb').live('click', function() {
if(!$(this).hasClass('hvThumbSel')) {

var from = '960px';
var to = '-960px';
var thisIndex = $(this).index()

// move left or right
if(curVid < thisIndex) {
from = '-960px';
to = '960px';
}

curVid = thisIndex;
var thisVid = $('.jCurVid')
slide(thisVid, vidArray[curVid], from, to, '0px', 'jCurVid');
} else {
restartVideo();

                   }
});

// hover over thumnails

$('.hvThumb:not(".hvThumbSel")').live('mouseover', function() {
$(this).addClass('hvThumbHov') 
});

$('.hvThumb').live('mouseout', function() {
$(this).removeClass('hvThumbHov') 
});


$('#jhvArrowPrev, #jhvArrowNext').live('mouseover', function() {
overArrows = true; 
});

$('#jhvArrowPrev, #jhvArrowNext').live('mouseout', function() {
overArrows = false; 
});

$('.jHovShow').live('mouseover', function() {
var showDiv = $(this).attr('id') + '_div';
$('#'+showDiv).show().siblings().hide();
 });

$('#formSubmit').live('click', function(e) {
  e.preventDefault();
  submitForm();
});

$('#aForm .formA').live('click',function() {
  $(this).parent().find('.formMessage').fadeOut();

})

$('#jqInterAccept').live('click',function() {
  writeCookie('managed_dc_audience', 'accepted', '400', '/', 'dfaus.com', '' )
  var redirect = document.location.href.split('=') [1]
  document.location.href=redirect;
});

// end LIVE

// called by the video player to resize its parent div to be the same size
function getDims(wd,ht,id,morph){
if (wd) {
$('#'+id).width(wd);
}
if (ht) {
// if sent height is more than current height then run animation
if (ht > $('#'+id).height() && morph == true) {
 $('#'+id).animate( { height:ht}, 1000 )

} else {
$('#'+id).height(ht);
}
}
}

function readCookie(nam) {
            var tC = document.cookie.split('; ');
            for (var i = tC.length - 1; i >= 0; i--) {
            var x = tC[i].split('=');
            if (nam == x[0]) {
            return unescape(x[1]);
}
}
             return null;
}            

function writeCookie( name, value, expires, path, domain, secure )

{
var today = new Date();
today.setTime( today.getTime() );
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function delete_cookie (nam) {
  var cookieDate = new Date ( );
  cookieDate .setTime ( cookieDate .getTime() - 1 );
  document.cookie = nam += "=; expires=" + cookieDate .toGMTString();
}


function restartVideo() {
//$('.jCurVid .videoPoster').show();
$('.jCurVid').find('.jOverview').show();
$('.jCurVid').find('.jSummary').hide();
$('#hvVideo_' + curVid + '_tt_0').show().siblings().not('.cards').hide();
switchVid(curVid)



}

function submitForm() {
var errorCount = 0;
  $('#aForm .formA').each(function() {
    if($(this).hasClass('required') ) { 
      if($(this).hasClass('email') && !checkEmail($(this).val()) && $(this).val() !='' ) {
 $(this).parent().find('.formMessage').text('Invalid email').show();
errorCount ++
      } else if ($(this).val() =='') {
        $(this).parent().find('.formMessage').text('Required').show();
errorCount ++
      }
    }
  });

      if(errorCount == 0) {
        $('.buffer').show();

var emailToVal = ['kim.ginsburg@dimensional.com','Tasha.Stenning@dimensional.com'];
var emailFromVal = $("#formEmail").val();
var nameVal = $("#formName").val();
var companyVal = $("#formCompany").val();
var phoneVal = $("#formPhone").val();
var mesVal = $("#formMessage").val();
var subjectVal = '[Web Contact] ';
var hrefVal = document.location.href
var hrefVal = document.location.href
var textVal=mesVal + '\n\n'+ nameVal + '\n' + companyVal + '\n' + phoneVal + '\n' + emailFromVal; 

//var dataString = 'subj=' + subjectVal + '&href=' + hrefVal+ '&dest_addr='+ emailToVal+ '&sorc_addr=' + emailFromVal+ '&text=' + textVal;  
var wsDataString = 'subj=' + '[Web Contact BCC. Original sent to ManagedDC]' + '&href=' + hrefVal+ '&dest_addr='+ 'website@dimensional.com' + '&sorc_addr=' + emailFromVal+ '&text=' + textVal;
var rmDataString = 'subj=' + subjectVal + '&href=' + hrefVal+ '&dest_addr='+ 'redmine@dimensional.com' + '&sorc_addr=' + 'greg.daem@dimensional.com' + '&text=' + textVal + '\nTracker: Public Site Inquiry\nCategory: Dimensional Managed DC';

$.ajax({  
  type: "POST",  
  url: "http://www.dfaus.com/mt/mt.cgi?__mode=dimensionalmail",  
  data: wsDataString});

$.ajax({  
  type: "POST",  
  url: "http://www.dfaus.com/mt/mt.cgi?__mode=dimensionalmail",  
  data: rmDataString});


      for(var i=0; i<emailToVal.length; i++) {
var dataString = 'subj=' + subjectVal + '&href=' + hrefVal+ '&dest_addr='+ emailToVal[i] + '&sorc_addr=' + emailFromVal+ '&text=' + textVal;  

$.ajax({  
  type: "POST",  
  url: "http://www.dfaus.com/mt/mt.cgi?__mode=dimensionalmail",  
  data: dataString,  
  success:function() {  
$('#formSent').fadeIn()
$('.buffer').hide();
  }, error:function(xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
  }
});  
      }
      }
}


function checkEmail(address) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(address);
}


function fadePoster() {
$('.jCurVid .videoPoster').fadeOut('slow');
}

// generic image swap
function swapImage(img,mod) {
if($(img).is('img') || $(img).is('input')) {
thisImg = $(img);
} else {
thisImg = $(img).find('img')
};
thisSrc = $(thisImg).attr('src');
thisType = thisSrc.substring(thisSrc.lastIndexOf('.'),thisSrc.length);
thisBtn = thisSrc.substring(0,thisSrc.lastIndexOf('_'));
isOn = thisSrc.substring(thisSrc.lastIndexOf('_'),thisSrc.lastIndexOf('.'));
if(isOn != '_mute') {
$(thisImg).attr({'src': thisBtn + '_' + mod + thisType })
}
}

// slide videos
function slide(id1, id2, pos1, pos2, pos3, cssclass) {
$('.jCurVid .videoPoster').show();
$('.jCurVid').find('.jOverview').show();
$('.jCurVid').find('.jSummary').hide();
$('#hvVideo_' + curVid + '_tt_0').fadeIn().siblings().not('.cards').hide();

$(id1).animate( {left: pos1}, 1000).removeClass(cssclass);
$('#'+id2).css({left: pos2}).animate( { left: pos3}, 1000).addClass(cssclass);
$('#thumb_'+curVid).addClass('hvThumbSel').siblings('.hvThumbSel').removeClass('hvThumbSel hvThumbHov');
$('#jVideoDiv').animate( { left: pos1}, 1000, function() {
//$('#jVideoDiv').hide().css({left: '0px'}).show();
$('#jVideoDiv').css({left: '0px'});
switchVid(curVid)
showArrows();

                                      

})
}

function slideBlog(thisBlog, thisDot, pos1, pos2) { 
$(thisBlog).animate( { left: pos1}, 1000).removeClass('jCurBlog');
$('#hc_'+curBlog).css({left: pos2}).animate( { left: '0px'}, 1000).addClass('jCurBlog');
$(thisDot).addClass('hcDotSel').find('img').attr({src: 'images/blog_dot_on.gif'})
$(thisDot).siblings().removeClass('hcDotSel hcDotHov')
$(thisDot).siblings().find('img').attr({src: 'images/blog_dot_off.gif'});
}

// tell swf to change videos
function switchVid(thisVid) {
$('.jCurVid').find('.jSummary').hide();
var thisPlayer = $("#player").get(0);
thisPlayer.changeVid(thisVid);
}

// called by video player when it hide/shows controls
function hideArrows() {
if(!overArrows) {
$('#jhvArrowPrev, #jhvArrowNext').fadeOut();
}
}

function showArrows() {
$('#jhvArrowPrev, #jhvArrowNext').fadeIn();
}

function nextVideo() {
$('#jhvArrowNext').click();
}

function fadeOverview() {
$('.jCurVid').find('.jOverview').fadeOut('slow'); 
}

function videoOver() {
$('.jCurVid').find('.jSummary').fadeIn(1000).siblings().fadeOut();
$('.jCurVid').find('.videoPoster').fadeIn(1000)
} 

function showTitle(tt) {
var thisTitle = $('#hvVideo_' + curVid + '_tt_' + tt)
$(thisTitle).fadeTo('slow',1).nextAll('.txtTitleVideo').hide();
$(thisTitle).prevAll('.txtTitleVideo').hide()//.siblings().not('.cards').hide();



//$('#hvVideo_' + curVid + '_' + tt).fadeIn('slow').prevAll().not('.cards').fadeTo('slow', 0.3)//.siblings().not('.cards').hide();
}

// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);

// cufon setup
Cufon.replace('.txtTitle, .hvThumbText, .txtSectionTitle, .imageMe, .txtArticleTitle',{hover: true, fontFamily: 'Avenir LT'})
('.imageMeB, .blogItemDate',{hover: true, fontFamily: 'Avenir Bold'})
