// language variables for search etc.


var searchText = 'Search';
var useLocation = 'http://fr.dfaca.com/';
var chapText = 'Chapters';
var hideText = 'hide';
var showText = 'show';
var validEmail = 'Please enter a valid email'
var lang = '';

//var setLoc = readCookie('dfaCountry')
//var thisLoc = document.location.href;
//redirect to language homepage if that's the last language viewed
//if(setLoc != useLocation.split('//')[1] && setLoc!='' && setLoc != null && thisLoc.split('.com')[1] == '/') {
//document.location.href = 'http://'+setLoc;
//}


var toggled=false;

// video player setup
$(document).ready(function () {

  $('.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,
        flashvars: {
        xmlFile: thisVideoXml
      }
    });  
  }); 

// drop down goto url.  Any drop down with id="jqJumpList" will go to the url in the drop down value
  $('#jqJumpList').change(function() {
if($(this).val()!=''&& $(this).val().substring(0,4) != 'http') {
window.location = 'http://fr.dfaca.com/' + $(this).val();
} else if($(this).val()!='') {
window.location = $(this).val();
}
    });

  $('.mediaSwitch').hover(function() {
    $('.mediaSwitchOps', this).stop(true, true).slideDown();
  }, function() {
    $('.mediaSwitchOps', this).stop(true, true).slideUp();
  });

  $('.mediaSwitchOp').hover(function() {
    $(this).addClass('bgMedGray');
  }, function() {
    $(this).removeClass('bgMedGray');
  });

  $('.mediaSwitchOp').live('click', function(){
    var thisPic = $(this).attr('id');
    $('#'+thisPic + 'Pic').show().siblings('img').hide();
    $('#'+thisPic + 'Num').show().siblings().hide();
    $('#'+thisPic + 'Disc').show().siblings().hide();

  });


// share stuff
var fbTitle = $('#jqFacebook').attr('href')
var liTitle = $('#jqLinkedin').attr('href')
$('#jqFacebook').attr('href', 'http://www.facebook.com/share.php?u=' + document.location.href + '&t=' + fbTitle );
$('#jqTwitter').attr('href', 'http://twitter.com/home?status=Currently%20reading%20' + document.location.href);
$('#jqDel').attr('href', 'http://del.icio.us/post?v=4&amp;url=' + document.location.href + '&title=' + fbTitle );
$('#jqLinkedin').attr('href', 'http://www.linkedin.com/shareArticle?mini=true&url=' + document.location.href + '&title=' + liTitle );

$("#shareSubmit").click(function(){
var emailToVal = $("#shareTo").val();
var emailFromVal = $("#shareFrom").val();
var textVal = $("#shareMessage").val();
var subjectVal = $("#shareSubject").val();
var hrefVal = document.location.href
var dataString = 'subj=' + subjectVal + '&href=' + hrefVal + '&dest_addr='+ emailToVal+ '&sorc_addr=' + emailFromVal+ '&text=' + textVal;  

if(emailToVal == '' || emailToVal == validEmail ) {
$("#shareTo").val(validEmail )
$("#shareTo").addClass('txtDRed')
return false;
}

if(emailFromVal == '' || emailFromVal == validEmail ) {
$("#shareFrom").val(validEmail )
$("#shareFrom").addClass('txtDRed')
return false;
}

$.ajax({  
  type: "POST",  
  url: "http://www.dfaus.com/mt/mt.cgi?__mode=dimensionalmail",  
  data: dataString,  
  success: function() {  
$('.shareEmail').slideToggle('fast')
$('#shareSent').show();
}
});
return false;
});


$('.jqTabs .jqTab, .jqTabs .jqTabAll').hover(function() {     
$(this).not('.tabSel').removeClass('tabUnSel')     
},function(){    
$(this).not('.tabSel').addClass('tabUnSel')
});


// accordian animation for onDemands with multiple chapters
$('.accordian ul').addClass('none');
// hide all items
$('.accordian ul').hide();
//show the first
$('.accordian ul:first').show();
$('.accordian ul:first').parent().addClass('bgLightGray');
$('.accordian li a').click(function() {
// show next sibling of the clicked row
var clickedRow = $(this).next();  
    if((clickedRow.is('ul')) && (clickedRow.is(':visible'))) {
        return false;
    }
if((clickedRow.is('ul')) && (!clickedRow.is(':visible'))) {
// hide current
       $('.accordian ul:visible').slideUp('normal');
       clickedRow.slideDown('normal');
// add an overiding gray css class to prevent orange hover
$(this).parent().addClass('bgLightGray')
// remove the override from other items
$(this).parent().siblings().removeClass('bgLightGray')
        clickedRow.parent().removeClass('cornerOff');
        $(this).parent().siblings().addClass('cornerOff')
        return false;
        }
     }
);

// orange hover
$(".hovOrange").hover(
function(){
$(this).addClass("bgOrange");
},
function() {
$(this).removeClass("bgOrange");
}
);

// launch button hover
$('.btnDiv').hover(function() {
$(this).find('.thumbImg').addClass('borderOrange')
$(this).find('.btnImg').attr("src","images/buttons/launch_on.gif");
}, function() {
$(this).find('.thumbImg').removeClass('borderOrange')
$(this).find('.btnImg').attr("src","images/buttons/launch_off.gif");
});

// mouseover buttons
var btnSrc;
    $('.jqBtn').hover(function() {
        btnSrc = $(this).find('img').attr('src');       
        var dot = btnSrc.lastIndexOf('.');
        var fName = btnSrc.substr(0,dot);
        var fType = btnSrc.substr(dot,btnSrc.length);
        $(this).find('img').attr('src', fName+ '_over' + fType);  

    },function() {
       $(this).find('img').attr('src', btnSrc);
    });
    
    $('.jqBtn').each(function() {
        preSrc = $(this).find('img').attr('src');        
        var dot = btnSrc.lastIndexOf('.');
        var fName = btnSrc.substr(0,dot);
        var fType = btnSrc.substr(dot,btnSrc.length);         
        preload(fName+ '_over' + fType)  
    });

// search stuff
var isFocused = false;
// add default text
if($('#searchBoxInput').val() === '') {
         $('#searchBoxInput').val(searchText );
      }

$('#searchBoxInput').focus(function() {
isFocused = true;   
$(this).addClass('searchBoxInputOver');   
// remove default text on focus
if($(this).val() === searchText) {
         $(this).val('');
      }
});

$('#searchBoxInput').blur(function() {
isFocused = false;
$('#searchBoxForm').stop().animate({height:20},300,"linear")
$(this).removeClass('searchBoxInputOver');
if($(this).val() === '') {
$('#searchBoxBtn').removeClass('searchFocus');
$('#searchBoxBtn').addClass('searchMute');
        $(this).val(searchText);
    }
});

// animate search box
$('#searchBoxInput').hover(function() {    
$('#searchBoxForm').stop().animate({height:38},300,"linear")
}, function(){
   if(isFocused == false) {
$('#searchBoxForm').stop().animate({height:20},300,"linear")
$(this).removeClass('searchBoxInputOver');
}
});

// table striping Any table with the class 'striped' will be striped
$('table.jqStriped').each(function() {
        //$(this).find('tbody tr').not('.noStripe').not([th]).filter(':even').addClass('bgLightGray');
        $(this).find('tbody tr:not([th]):odd').not('.noStripe').addClass('bgLightGray');
});

// table row hover
$('.jqRowHov td').hover(function() {
$(this).parent().find('td').addClass('bgMedGray')
},function() {
$(this).parent().find('td').removeClass('bgMedGray')
});

// hover for nav incase no css hover
$('.navTab li').hover(function() {
     $(this).addClass('navHov ');
     },function(){    
 $(this).removeClass('navHov ');
});

// keep top level nav item highlighted
$('.navTabSub').hover(function() {
     $(this).parent().addClass('bgMenuBlue');
     },function(){    
 $(this).parent().removeClass('bgMenuBlue');
});

// go button hover
$('#searchBtn').hover(function() {
     $(this).css({'background-image':"url('images/buttons/btn_go_over.png')"})
     },function(){   
$(this).css({'background-image':"url('images/buttons/btn_go.png')"})
   });
}); // end on document ready


// 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);
}
}
}

// preload images for hovers
function preload() {
    for(var i = 0; i<arguments.length; i++) {
        $("img").attr("src", arguments[i]);
    }
}

// used by video player to create html chapter links and descriptions
function drawChapters(div,chp) {
var vidPar = $('#'+div);
var chapParId = 'chaps' + div;
vidPar.after('<div class="mediaChapters" id="' + chapParId + '"><div class="mediaChapter mediaChapHide"><span class="txt txtB">' + chapText + '</span> (<span class="txtBlue txtXSmall hideChaps">' + hideText + '</span>)</div><div class="mediaChapCont"></div></div>')
var chapsShow = true;
$('.hideChaps').click(function() {
if(chapsShow == true) {
$('.mediaChapCont').hide();
$(this).text(showText);
chapsShow = false;
} else {
$('.mediaChapCont').show();
$(this).text(hideText)
chapsShow =true;
}    
});

for(i=chp.length-1; i>=0; i--) {
$('#' + chapParId).find('.mediaChapCont').append('<div class="mediaChapter dispBlock"><a href="javascript:sendCue(' + chp[i][2] + ')"><span class="txtBlue txtB dispBlock">' + chp[i][0] + '<span class="txt txtXSmall txtP"> (' + chp[i][3] + ')</span></span><span class="txt">' + chp[i][1] + '</span></a></div>')
}
}

// send cuepoint back to video player for chapter jumps
function sendCue(txx,chap) {
var tp = $("#player").get(0)
tp.cp(txx,chap);
}


// get video player for external interface calls
function getMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

// read a cookie - used by video player to decide if the video bumper should be shown
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 adobe_load(od) {
window.open(od,'','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
}

// div sorting
var titleSort = 'des';
var dateSort = 'des';
var authorSort = 'des';
var sortDir = 'des';

function setSortDir(type) {
// sort title fields
 if(type == 'jqSortTitle') {
  if(titleSort == 'asc') {
     titleSort = 'des';
     sortDir = 'des';
  } else {
    sortDir = 'asc';
    titleSort = 'asc'
   }
  sortDivs('jqSortTitle');
 }
// sort by date fields
 if(type == 'jqSortDate') {
  if(dateSort == 'asc') {
     dateSort = 'des';
     sortDir = 'des';
  } else {
    sortDir = 'asc';
    dateSort = 'asc'
   }
  sortDivs('jqSortDate');
 }

// sort by Author fields
if(type == 'jqSortAuthor') {
  if(authorSort == 'asc') {
     authorSort = 'des';
     sortDir = 'des';
  } else {
    sortDir = 'asc';
    authorSort = 'asc'
   }
  sortDivs('jqSortAuthor');
 }
}


function sortDivs(type) {
var rows = [];
// put html of divs to be sorted in array
  $(".libModule").each(function(){
  var sortContent = $(this).find(".libModuleInfo div." +type).text().toLowerCase();
 rows[rows.length] = [sortContent,this];
  });

// sort array
if(sortDir == 'asc') {
  rows.sort(
   function(a,b){
    if (a[0] < b[0]) {
     return -1
    } else if (a[0] > b[0]) {
     return 1
    } else {
     return 0;
    }
   }
  );
}

else {
rows.sort(
   function(a,b){
    if (a[0] > b[0]) {
     return -1
    } else if (a[0] < b[0]) {
     return 1
    } else {
     return 0;
    }
   }
  );
}
// rewrite divs in order of sorted array
  $.each(rows, function() {
    this[1].parentNode.appendChild(this[1]);
   }
  );
}

// language button selection
$('#navLoc a').live('click', function(event) {
event.preventDefault();
delete_cookie ('dfaCountry')
var thisHref = $(this).attr('href');

var newLoc = thisHref.split('//')[1];
newLoc = newLoc.split('.com')[0];

writeCookie('dfaCountry', newLoc+'.com/', 90, '/', 'dfaeurope.com', '' )
document.location = thisHref;
});


// div sorting links
$('.jqSortBtnTitle').live('click', function() {
setSortDir('jqSortTitle');
});

$('.jqSortBtnAuthor').live('click', function() {
setSortDir('jqSortAuthor');
});

$('.jqSortBtnDate').live('click', function() {
setSortDir('jqSortDate');
});

// share popup
$('.jqShowShare').live('click', function() {
$('#shareContent').toggle();
});

// slide a div
$('.jqDrawerBtn').live('click', function() {
$(this).siblings('.jqDrawer').slideToggle('fast')
$('#shareSent').hide();
});

$("#shareTo").live('click', function() {
if($(this).val() == 'Please enter a valid email') {
$(this).val('')
$(this).removeClass('txtDRed')
}
});

$("#shareFrom").live('click', function() {
if($(this).val() == 'Please enter a valid email') {
$(this).val('')
$(this).removeClass('txtDRed')
}
});


// open window for adobe onDemands
  $('.jqOnDemand').live('click', function() {
       var od = $('#jqOnDemandUrl').val();      
       window.open(od,'','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
   
  });

// hide/show tab content
  $('.jqTabs .jqTab').live('click', function() {
     $(this).removeClass('tabUnSel').addClass('tabSel')
     $(this).siblings().addClass('tabUnSel').removeClass('tabSel')
      var whichDiv = $(this).attr('id') + 'Div'
     $('#' + whichDiv).show().siblings('.jqTabDiv').hide();

  });
 $('.jqTabs .jqTabAll').live('click', function() {
     $(this).parent().parent().siblings('.jqTabDiv').show();
     $(this).removeClass('tabUnSel').addClass('tabSel')
     $(this).siblings().addClass('tabUnSel').removeClass('tabSel')
  });
  
 // hide all siblings of any element with class="jqHideSiblings"
  $('.jqHideSiblings').live('click', function() {
       if(toggled==false){$('.jqHideSiblings').html('Show'); toggled=true;}
       else{$('.jqHideSiblings').html('Hide');toggled=false;}
       $(this).parent().siblings().toggle();
       return false;
   });
   



// Glossary stuff
var currGloss = ''
var item;
// get each glossary text and text position from the main body text
  $('.jqGloss').live('mousemove', function(e) {
     currGloss = $(this).text().toLowerCase();  

     // find every glossary item hidden on the page
     $('.jqGlossMatch').each(function() {
         var currItem = $(this).text().toLowerCase();

         // if it matches the body text item position and show the div
              if(currItem  == currGloss || currItem+'s'  == currGloss ) {              
              item = $(this).parent().parent().parent();
              item.show();
                 if(e.pageX+item.width() < $(window).width()) {
                 item.css({top: e.pageY-item.height()-20}).css({left: e.pageX-20});
                 item.parent().find('.jqGlossPoint').css({left: 20});
                 } else {
                 item.css({top: e.pageY-item.height()-20}).css({left: e.pageX-item.width()+20})
                 item.parent().find('.jqGlossPoint').css({left: item.width()-20});
                 }
              }
     });
   });

 $('.jqGloss').live('mouseout', function() {
    item.hide();
});

// un-mute go button
$('#searchBoxInput').live('keyup',function() {
$('#searchBoxBtn').addClass('searchFocus');
$('#searchBoxBtn').removeClass('searchMute');
});



// cufon text replacement

Cufon.replace('.txtSection',{hover: true, fontFamily: 'Avenir LT'})
('.txtTitle')
('.txtCufTabs',{hover: true, fontFamily: 'Avenir Bold'})
('.leftModuleTitle',{fontFamily: 'Avenir LT'})
('.txtMediaTitle',{hover: true, fontFamily: 'Avenir Bold'})
('.leftModuleTitleB',{fontFamily: 'Avenir Bold'})
('.txtSubTitle',{fontFamily: 'Avenir Bold'})
('.txtChartTitle',{fontFamily: 'Avenir Bold'})
('.nextStepsTitle',{fontFamily: 'Avenir Bold'})
('.imageMe',{fontFamily: 'Avenir LT'})
('.imageMeB',{fontFamily: 'Avenir Bold'})
('.imageMeHov',{hover: true, fontFamily: 'Avenir LT'})
('.imageMeBHov',{hover: true, fontFamily: 'Avenir Bold'});


// 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||'100%',height:a.height||'100%',style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"transparent";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);






