//BlackBerry
function detectBlackberry() {
    var deviceBB = "blackberry";

    //Initialize user agent string and convert it to lower case.
    var uagent = navigator.userAgent.toLowerCase();

    //**************************
    // Detects if the current browser is some kind of BlackBerry.

    if (uagent.search(deviceBB) > -1)
        window.location.href = "blackberry/index.html"
    else
        return false;

}

// APPLING SCROLL
function homeFamous(hash){
  if( hash == undefined || hash == ''){
    hash = window.location.hash
  }
  if ( jQuery.browser.msie ){
    hash = '#'+hash.split("#")[1];

    if(hash == '#undefined'){
      setTimeout(function(){
       location.reload();
      }, 500);
    }
  }


  $.ajax({
  url: 'documentos/xml/famous-no-video.xml',
    dataType: (jQuery.browser.msie) ? "text" : "xml",
    success: function(event, xhr, settings){

      if ( jQuery.browser.msie )
      {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

        xmlDoc.async = "false";
        xmlDoc.loadXML(settings.responseText);
        settings = xmlDoc;

        var famous = settings.documentElement.childNodes;

        if(hash == '') {
          hash = '#'+settings.documentElement.firstChild.getAttribute('hash');
        }
        if( window.location.hash == '') {
          window.location.hash = settings.documentElement.firstChild.getAttribute('hash');
        }
      }
      else
      {
        famous = event.firstChild.childNodes;

        if(hash == '') {
          hash = '#'+event.firstChild.firstElementChild.attributes[2].nodeValue;
        }
        if( window.location.hash == '') {
          window.location.hash = event.firstChild.firstElementChild.attributes[2].nodeValue;
        }
      }

      // FEED SCROLL
      $('#diagonal-scroll ul li a').live("mouseenter mouseleave", function(event) {

        if ( event.type == "mouseenter" ) {
          $(this).css({
            opacity: 1
          });
        } else {
          $(this).css({
            opacity: 0.2
          });
        }
      });

      var htmlFamous = '<div id="figure">';
          htmlFamous += '<img src="images/persona/'+getAttributeHash('image', hash, famous)+'2.png" alt="'+getAttributeHash('image', hash, famous)+'">';
          htmlFamous += '<p>More About '+getAttributeHash('name', hash, famous)+'</p><ul>';

          if(getAttributeHash('first-link', hash, famous)) {
            htmlFamous += '<li><a href="'+getAttributeHash('first-link', hash, famous)+'" target="_blank">'+getAttributeHash('first-tittle-link', hash, famous)+'</a></li>';
          }

          if(getAttributeHash('second-link', hash, famous)){
            htmlFamous += '<li>/</li><li><a href="'+getAttributeHash('second-link', hash, famous)+'" target="_blank">'+getAttributeHash('second-title-link', hash, famous)+'</a></li>';
          }

          if(getAttributeHash('third-link', hash, famous)){
            htmlFamous += '<li>/</li><li><a href="'+getAttributeHash('third-link', hash, famous)+'" target="_blank">'+getAttributeHash('third-title-link', hash, famous)+'</a></li>';
          }

          htmlFamous += '</ul><a href="campaign.html" class="replacement campaign-link" title="About the Campaign">About the Campaign</a>';
          htmlFamous += '</div><div id="text-star">'+getAttributeHash('text', hash, famous)+'</div>';
          // htmlFamous += '<div id="video-star"><div id="flashEmbed">&nbsp;</div></div>';


      $('#famous-space').html(htmlFamous);

      // $('#other-stars h3').text(getAttributeHash('name', hash, famous));

      // if (swfobject.hasFlashPlayerVersion("8.0.0")) {
      //  swfobject.embedSWF('http://www.youtube.com/e/'+getAttributeHash('youtubeID', hash, famous)+'?version=3&enablejsapi=1',"flashEmbed", "560", "345", "8", null, null, { allowScriptAccess: "always", wmode: "opaque" }, { id: "myytplayer" });
      // }
      // else {
      //  var videoDiv = document.getElementById('flashEmbed');
      //  videoDiv.innerHTML = '<object width="560" height="345"><param name="movie" value="http://www.youtube.com/e/'+getAttributeHash('youtubeID', hash, famous)+'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/e/'+getAttributeHash('youtubeID', hash, famous)+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="345"></embed></object>';
      // }
    }
  });
}


function loadScrollFamous () {

  $.ajax({
  url: 'documentos/xml/famous.xml',
    dataType: (jQuery.browser.msie) ? "text" : "xml",
    success: function( event, xhr, settings){

      if ( jQuery.browser.msie )
      {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

        xmlDoc.async = "false";
        xmlDoc.loadXML(settings.responseText);
        settings = xmlDoc;

        var famous = settings.documentElement.childNodes;

        window.location.hash = settings.documentElement.firstChild.attributes[2].nodeValue;

      }
      else
      {
        var famous = event.firstChild.childNodes;
        window.location.hash = event.firstChild.firstElementChild.attributes[2].nodeValue;
      }




      for (var i=0; i < famous.length; i++) {
        var famousName = $(famous[i]).attr('name');
        var famousImage = $(famous[i]).attr('image');
        var famousHash = $(famous[i]).attr('hash');

        var famousItem = '<li><a href="#'+famousHash+'" name="#'+famousHash+'" class="replacement" style="background: url(images/persona/thumb-'+famousImage+'.gif) bottom right no-repeat" title="'+famousName+'">'+famousName+'</a></li>'

        $('#diagonal-scroll ul').append(famousItem);

        $('#diagonal-scroll ul li a').css({
          opacity: 0.2
        });

      };

      function mycarousel_initCallback(carousel) {

          jQuery('#next-diagonal-item').bind('click', function() {
              carousel.next();
              return false;
          });

          jQuery('#prev-diagonal-item').bind('click', function() {
              carousel.prev();
              return false;
          });
      };
      $('#diagonal-scroll ul').jcarousel({
        initCallback: mycarousel_initCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null
      });

      $('#diagonal-scroll ul li a').bind( 'click', function(){
        $('body').animate({ scrollTop: 220}, 400);
        $('html').animate({ scrollTop: 220}, 400);
        homeFamous($(this).attr('href'));

        $('#diagonal-scroll ul li a').removeClass('active-famous');
        $(this).addClass('active-famous');

        if( $.browser.msie){
          var hashIe = $(this).attr('name');

          hash = hashIe

          return false;
        }

      });

    }
  });

}

function getAttributeHash (atribute, hash, xml, hashIe) {
  var strReturn = '';
  for (var i=0; i < xml.length; i++) {
    var strNodeAtt = $(xml[i]).attr(atribute);
    var famousHash = $(xml[i]).attr('hash');
    if (hash == '#'+famousHash) {
      strReturn = strNodeAtt;
    };
  };
  return strReturn;

}

// POSITION PINS FOR CONTACT MAP
function loadContactPins(){

  $.ajax({
  url: 'documentos/xml/countries.xml',
    dataType: (jQuery.browser.msie) ? "text" : "xml",
    tipe: 'GET',
    success: function(event, xhr, settings){

      if ( jQuery.browser.msie )
      {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

        xmlDoc.async = "false";
        xmlDoc.loadXML(settings.responseText);
        settings = xmlDoc;

        countries = settings.documentElement.childNodes;
      }
      else
      {
        countries = event.firstChild.childNodes;
      }

      for (var i=0; i < countries.length; i++) {
        var countryId = $(countries[i]).attr("id");
        var countryName = $(countries[i]).attr("name");
        var countryX = $(countries[i]).attr("positionx");
        var countryY = $(countries[i]).attr("positiony");

        var pinCountry = '<div class="country-pin" id="'+countryId+'" style="top:'+countryY+'px;left:'+countryX+'px;"><span><p>'+countryName+'</p><small class="replacement">here</small></span>'

        $('#map-location').append(pinCountry).find('.country-pin').hide();
        $('.country-pin#undefined').remove();
      };

      $('.country-pin').fadeIn('slow');
      $('.country-pin span').corner('6px');
    }
  });


  // HOVER CONTACT PIN
  $('.country-pin').live({
     mouseenter:
        function(){
          $(this).addClass('master');
          var spanPin  = $(this).find('span');
          var widthPin = spanPin.width();
          spanPin.css({
            marginLeft: - 4 - widthPin /2
          });

          var self = $(this);

          timeout = setTimeout( function(){
            $(self).find('span').show('fade', 250);
          }, 200);
        },
     mouseleave:
        function()
        {
          clearTimeout(timeout);
          $(this).find('span').hide();
          $(this).removeClass('master');
        }
    });


  // CLICK CONTACT PIN
  $('.country-pin').live("click", function() {

    $('.continent li').removeClass('activePin');

    var idPin = $(this).attr('id');

    $('body').animate({ scrollTop: 800}, 400);
    $('html').animate({ scrollTop: 800}, 400);

    setTimeout( function(){
      $('.'+idPin).addClass('activePin').show('puff', 300);
    },500);


  });


  // HOVER CONTACT TEXT
  $('#map-location .continent li').stop().bind("mouseover mouseout", function(event) {

    var listName  = $(this).attr('class');

    var spanPin  = $('#'+listName).find('span');
    var widthPin = spanPin.width();

    spanPin.css({
      marginLeft: - 4 - widthPin /2
    })

    if ( event.type == "mouseover" ) {
      $('.country-pin span').hide();
      $('#'+listName).addClass('master').find('span').show('puff', 200);
    } else {
      $('#'+listName).removeClass('master').find('span').hide();
    }
  });

}

function contentFly(){
  $("#wrap-content ul#list-star a").fancybox({
    autoScale: false
  });

  $("#more-videos ul a").fancybox({
    'type': 'iframe',
    'titleFormat'		: function() {
      if(window.FB===undefined) {

      } else {
        return '<span id="fancybox-title-over"><ul id="ul-share"><li><a href="'+this.href+'" name="Link Facebook Itaú" title="'+this.href+'" class="replacement facebook-link-sharing">Facebook</a></li> <li><a href="'+this.href+'" name="Link Twitter Itaú" title="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod.'+this.href+'" class="replacement twitter-link-sharing">Twitter</a></li> </ul></span>';
      }
			appItau.mediaShare.onCLick();
		}

  });

}

function homeMotion(){

  $('#more-videos li').bind("mouseenter mouseleave", function(event) {
    if ( event.type == "mouseenter" ) {
      $(this).find('span').stop().animate({
        opacity: 1,
        top: '0'
      }, 400, 'easeInOutQuad');
    } else {
      $(this).find('span').stop().animate({
        opacity: 0,
        top: "68px"
      });
    }
  });
}

function newsAlign(){
  var parentHeight = $('.content-news').parent().parent().height();
  $('.content-news').height(parentHeight-110);
}

function shareTwitter(linkName, linkHref, linkTitle) {
  var loadingHtml = '<div id="overlay-sharing">&nbsp;</div><div id="loading-sharing"><a href="#" id="close-sharing" class="replacement">x</a><p>Aguarde...</p></div>'
  $("body").append(loadingHtml);


  setTimeout(function(){
    $('#loading-sharing').remove();
    $('#overlay-sharing').remove();
  }, 3000)

  var url = "http://twitter.com/share";
  var text = encodeURIComponent(linkTitle);
  var centerW = window.screenX + (window.innerWidth - 540) / 2;
  var centerH = window.screenY + (window.innerHeight - 380) / 2;

  window.open(url + "?url=" + "" + "&text=" + text, "_blank", "width=540, height=380, toolbar=0, status=0 top=" + centerH + ", left=" + centerW + ", screenX=" + centerW + ", screenY=" + centerH);

}

function postToFeed(linkName, linkHref, linkTitle) {

  var loadingHtml = '<div id="overlay-sharing">&nbsp;</div><div id="loading-sharing"><a href="#" id="close-sharing" class="replacement">x</a><p>Aguarde...</p></div>'

  $("body").append(loadingHtml);

  // calling the API ...
  var obj = {
    method: 'feed',
    link: linkHref,
    // link: 'https://developers.facebook.com/docs/reference/dialogs/',
    picture: 'http://itauinter.gringodeploy.com.br/images/visual/itau.png',
    name: 'Itaú Internacional',
    caption: "",
    description: linkTitle
  };

  function callback(response) {

    if(response == null) {
      $('#loading-sharing p').html("Mensagem não Enviada");

      setTimeout(function(){
        $('#loading-sharing').remove();
        $('#overlay-sharing').remove();
      }, 3000);

    } else {
      $('#loading-sharing p').html("Mensagem Enviada com Sucesso");

      setTimeout(function(){
        $('#loading-sharing').remove();
        $('#overlay-sharing').remove();
      }, 3000);

    }
  }

  FB.ui(obj, callback);
}


appItau = {
  mediaShare: {
    onCLick: function(){
      // Twitter Share
      $(".twitter-link-sharing").live( 'click', function(){

        var linkName = $(this).attr("name");
        var linkHref = $(this).attr("href");
        var linkTitle = $(this).attr("title");

        shareTwitter(linkName, linkHref, linkTitle);

        return false;
      });

      // Facebook Share
      $(".facebook-link-sharing").live( 'click', function(){

        var linkName = $(this).attr("name");
        var linkHref = $(this).attr("href");
        var linkTitle = $(this).attr("title");

        postToFeed(linkName, linkHref, linkTitle);

        return false;
      });

      $("#close-sharing").live( 'click', function(){
        $("#loading-sharing").remove();
        $("#overlay-sharing").remove();

        return false;
      });

    }
  }
}

$(document).ready(function() {

  if(window.FB===undefined) {
   $(".facebook-link-sharing").remove();
  } else{
    FB.init({appId: "191769924232219", status: true, cookie: true});
  }

  appItau.mediaShare.onCLick();
  makeMenu();
  contentFly();
  if ( jQuery.browser.msie ) {
    $('.rounded-all').corner('6px');
    $('#all-footer ul li a').corner('6px');
    $('.continent ul li').corner('6px');
  }
  newsAlign();
});
 
