/* Author: CircusMarketing.com / Nextdart.com

*/

var curr_page = 1;
var data_news ;
var animacion_paginando = false;
var globalImagesArray = [];
var itemsDescriptions = [];
var viendoFicha = false;
var viendoContact = false;
var viendoAbout = false;
var primeraVezFicha = true;
var primeraVezScroll = true;
var fichaGlobalPos = '';
var globalIntervalInterfase1;
var globalIntervalInterfase2;
var load_item="";
var historyHizoClick=false;

var isEventSupported = (function(){
  var TAGNAMES = {
    'select':'input','change':'input',
    'submit':'form','reset':'form',
    'error':'img','load':'img','abort':'img'
  }
  function isEventSupported(eventName) {
    var el = document.createElement(TAGNAMES[eventName] || 'div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);
    if (!isSupported) {
      el.setAttribute(eventName, 'return;');
      isSupported = typeof el[eventName] == 'function';
    }
    el = null;
    return isSupported;
  }
  return isEventSupported;
})();

var myEventClick = isEventSupported('touchstart')? 'touchstart':'click';


$(document).ready(function(){
  
  document.title=globalSiteTitle;
  
  //prepare history
  // Prepare
	var History = window.History; // Note: We are using a capital H instead of a lower h
	if ( !History.enabled ) {
		 // History.js is disabled for this browser.
		 // This is because we can optionally choose to support HTML4 browsers or not.
		return false;
	}

	// Bind to StateChange Event
	History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
		//if (!historyHizoClick) console.log('uso browser back/fw');
		//processHistoryChange();
	});

  processHistoryChange();
 
  //init loading
  $("#page1, #page2").hide();
  $("#loading").css('height', $("body").height()+'px').fadeIn();
  loadXML();
  
  
  //animate intro
  $('#title').css('display', 'block');
  $('#title').animate({ opacity: 0 }, 0);
  $("#title").animate({'margin-left':'0px', 'opacity':'1'}, 1200, 'easeOutBounce');
  
  //navigation
  setTimeout(function(){
      var increment=0;
      var $nav = $("nav ul li");
      $nav.each(function(){
        var tmp_obj = $(this);
        
        //setup nav
        if ( $.inArray($(this).attr('category'), itemsNavActive)>-1) {
  
              setTimeout(function(objn){
                
                if ($.browser.msie) { 
                objn = $(tmp_obj); 
                $(objn).show();
                }
                else $(objn).fadeIn();
                
              }, increment, tmp_obj);
              increment+=200;
        }
      });
      
      $nav.bind(myEventClick, function(){
         
          historyHizoClick=true;
          if (viendoFicha) $("#close").trigger(myEventClick);
          if (viendoContact) { $("#contact, .title_suc").fadeOut(); viendoContact=false;}
          if (viendoAbout) { $("#about").fadeOut(); viendoAbout=false;}
          
          $("#flecha_der, #flecha_izq").fadeOut();
          $nav.find('a').removeClass('active');
          $(this).find('a').addClass('active');
          $("#page1").fadeOut();
          $("#loading").fadeIn();
          active_section = $(this).attr('category');
          
          curr_page = 1;
          
          if (active_section!='contact' && active_section!='about') loadFirstPage();
          else {
            
            if (active_section=='contact') displayContact();
            if (active_section=='about') displayAbout();
            
          }
          
      });
      
  }, 1000);
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  //FUNCTIONS
  
  function displayContact(){
    
      if (viendoContact) return;
      
      viendoContact=true;
      
      History.replaceState({detalle:0}, globalSiteTitle + " - Contact", "?"+active_section); 
      historyHizoClick=false;
      
      var pageHeight2 = ( $("body").height() - 90 );
    
      $("#contact").css({'height':pageHeight2+'px'});
      setTimeout(function(){
          $("#contact").fadeIn(function(){
          
              $("#loading").fadeOut();
              
              var intval = 400;
              
              $("#contact .title_suc").each(function(){
               
                    
                      var tmp_obj = $(this);
                      setTimeout(function(objn){
                        
                        if ($.browser.msie) { 
                            objn = $(tmp_obj); 
                            $(objn).show(contactAnimateAddress(objn));
                        }
                        else $(objn).fadeIn(contactAnimateAddress(objn));
                        
                      }, intval, tmp_obj);
                      intval+=500;
               
               
              });
              
          });
       }, 500);
  }
  
  function displayAbout(){
    
      if (viendoAbout) return;
      
      viendoAbout=true;
      
      History.replaceState({detalle:0}, globalSiteTitle + " - About Us", "?"+active_section); 
      historyHizoClick=false;
      
      var pageHeight2 = ( $("body").height() - 90 );
    
      $("#about").css({'height':pageHeight2+'px'});
      
      
      setTimeout(function(){
        
        setTimeout(function(){
          fixSlogan();
          fixFontSize();
          setupFichaScroll();
        }, 100);
        $("#about").fadeIn(function(){
            fixSlogan();
            fixFontSize();
            setupFichaScroll();
            $("#loading").fadeOut();
                     
        });
      }, 500);
  }
  
  function contactAnimateAddress(obj){
      $tmp = $(obj).find('.detail_suc')
      
      $tmp.animate({ opacity: 0, bottom:'50px' }, 0);
      $tmp.animate({'bottom':'0', 'opacity':'1'}, 600, 'easeOutBounce');
  }
  
  function processHistoryChange(){
     
      var myObj = $.deparam.querystring();
      var myObj = $.deparam.fragment();
      var State = History.getState();
      var path = document.location.pathname;
      var myhash = State.hash.substr(path.length, (State.hash.length-path.length));
      if ($.browser.msie) myhash = State.hash;
      
      //console.log(State.hash);        ///webcircus/v3/?people/2/detalle/item_26&_suid=13270168843800032762638704559754
      //?work/1/detalle/item_94
      //console.log("myhash: "+myhash); //?people/2/detalle/item_26&_suid=13270168843800032762638704559754
      //myhash: e/item_94
      
      
      
      if (State.hash != "/" && State.hash != "./" && State.hash != path) {
        
        var item_pos = 3;
        //if ($.browser.msie) item_pos--;
        var section_pos = item_pos-3;
        var page_pos = item_pos-2;
        
        load_item =    myhash.split('/')[item_pos];
        load_section = myhash.split('/')[section_pos];
        load_page =    myhash.split('/')[page_pos];
        
        if (typeof load_item == "undefined") {
          load_item = "";
        }
        
        
        if (typeof load_item != "undefined") {
          load_item = load_item.split('&')[0];
        }
        
        if (typeof load_section == "undefined") {
          load_section = "";
        }
        
        var is_contact = load_section.split('?')[1];

        if (typeof is_contact != "undefined"){
          if (is_contact.split('&')[0] == "contact") {
            load_item = "";
            load_section = "0?contact";
            load_page = "1";
          }
          if (is_contact.split('&')[0] == "about") {
            load_item = "";
            load_section = "0?about";
            load_page = "1";
          }
        }
        
        
        
        
        //console.log("load_section: "+load_section);
        active_section = load_section.split('?')[1];
        curr_page = load_page.split('&')[0];
        //console.log("active_section: "+active_section);
        var $nav = $("nav ul li");
        $nav.find('a').removeClass('active');
        $("nav ul li[category="+active_section+"]").find('a').addClass('active');
        
        if (typeof is_contact != "undefined") {
            if (is_contact.split('&')[0] == "contact") displayContact();
            if (is_contact.split('&')[0] == "about" ) displayAbout();
        }    
        
      }
      else{
      
      }
  
  }
  
  function prepareInternalLinks(){

      var siteURL = top.location.host.toString();
      var $internalLinks = $("a[href^='http://"+siteURL+"'], a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

      $internalLinks.unbind(myEventClick).bind(myEventClick, function(){
        $ref = $(this).attr('href');
        $ref = $ref.split('?');
        $ref2 = $ref[1].split('/');
              
        
        if ($ref2.length==2){
        
          var section = $ref2[0];
          var page = $ref2[1];
          
          viewItem("", section, page);
        
        } else if ($ref2.length==4){
        
          var item = $ref2[3].split('&')[0];
          var section = $ref2[0];
          var page = $ref2[1];
          
          viewItem(item, section, page);
        
        }
        
        return false;
      });
      
  }
  
  function viewItem(item, section, page){
          
          load_item =    item;
          active_section = section;
          curr_page = page;

          if (viendoFicha) $("#close").trigger(myEventClick);
          loadFirstPage();
          setTimeout(function(){$("#"+load_item).trigger(myEventClick);}, 2000);
          return;
          
  }
  
  function loadFirstPage(){
  
          $("nav ul li a").removeClass('active');
          $("nav ul li[category='"+active_section+"'] a").addClass('active');
          
          History.replaceState({detalle:0}, globalSiteTitle + " " + active_section, "?"+active_section+"/"+curr_page); 
          
          $("#page1 ul").html('');
          var counter =0 ;
          
          $(data_news).find('post').each(function(){  
  
            var $post = $(this);  
            var title = $post.find("title").text();
            var short_title = $post.find("short_title").text();
            var short_txt = $post.find("short").text();
            var image = $post.find("image").text();
            var category = $post.find("category").text();
            var link = $post.find("link").text();
            var cid = $post.find("id").text();;
            
            if (active_section==category) {
                
                $("#page1 ul").append('<li id="item_'+cid+'" title="'+title+'"><a href="'+link+'" style="background-image:url('+photos_path+"/"+image+');"></a></li>');
                $("#page1 ul li#item_"+cid).data('short', short_txt);
                counter++;
            }
          });
          
          clearInterval(globalIntervalInterfase1);
          clearInterval(globalIntervalInterfase2);
          
          setTimeout(function(){
          
              $("#loading").fadeOut();
              $("#page1, #page2").show();
              
              initialSetup('-'); //el '-' es dirección hacia adelante
              setupEvents() 
              
              globalIntervalInterfase1 = setInterval(function(){drawInterfase()}, 100);
              globalIntervalInterfase2 = setInterval(function(){fixFontSize()}, 20);
              
          }, 1000);
  }
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  function setupAfterDataReady(){

      $("#loading").fadeOut();
      $("#page1, #page2").show();

      $("#page1 ul li").live('mouseenter', function(){

        var curr = $(this);
        var div = $('div', curr);
        
        if ($(curr).find('div').size()==0) {
          $(curr).append('<div><span>'+$(curr).attr('title')+'</span></div>');
        }
        
        $(curr).find('div').fadeTo(300, 0.6);
        
        
      }).live('mouseleave', function(){
        
        var curr = $(this);
        
        $(curr).find('div').fadeOut(300);
        
      });

      if (active_section=='contact') {
          displayContact(); 
          globalIntervalInterfase1 = setInterval(function(){drawInterfase()}, 100);
          globalIntervalInterfase2 = setInterval(function(){fixFontSize()}, 20);
          return;
          }
      if (active_section=='about') {
          displayAbout(); 
          globalIntervalInterfase1 = setInterval(function(){drawInterfase()}, 100);
          globalIntervalInterfase2 = setInterval(function(){fixFontSize()}, 20);
          return;
          }

      initialSetup('-'); //el '-' es dirección hacia adelante
      setupEvents();
      
      
      if (load_item!="") {
        setTimeout(function(){$("#"+load_item).trigger(myEventClick);}, 1000);
      }
      
      globalIntervalInterfase1 = setInterval(function(){drawInterfase()}, 100);
      globalIntervalInterfase2 = setInterval(function(){fixFontSize()}, 20);

  }

  function initialSetup(direction){
  
    var incrementador = 0;
    
    var init_pos = (curr_page-1)*9;
    var end_pos  = init_pos+9;
    
    if (direction=='-'){
      var next_page_init_pos = end_pos;
      var next_page_end_pos  = end_pos+9;
    }
    else{
      var next_page_init_pos = init_pos-9;
      var next_page_end_pos  = init_pos;
    }
    
    $("#page2").html('<ul></ul>');
       

    var counter=0;
    var $startCategory = $(data_news).find('post:eq(0)');
    var tempCat = $startCategory.find('category').text();
    //console.log(active_section);
    $(data_news).find('post').each(function(){  

      
      
      var $post = $(this);  
      var title = $post.find("title").text();
      var short_title = $post.find("short_title").text();
      var short_txt = $post.find("short").text();
      var image = $post.find("image").text();
      var category = $post.find("category").text();
      var link = $post.find("link").text();
      
      //if (category!=tempCat) { counter=0;tempCat = category;}
      
      var cid = $post.find("id").text();;
          
      //mostrar página actual
      if (counter>=init_pos && counter<end_pos && active_section==category){
         
          setTimeout(function(obj){
        
          if ($.browser.msie) { obj = $("#page1 ul li#item_"+cid); }
          $(obj).fadeIn();
          
        }, incrementador, $("#page1 ul li#item_"+cid));
        incrementador+=100;
        
      }
      
      //armar página siguiente
      if (counter>=next_page_init_pos && counter<next_page_end_pos && active_section==category){
          $("#page2 ul").append('<li id="item_'+cid+'" title="'+title+'"><a href="'+link+'" style="background-image:url('+photos_path+"/"+image+');"></a></li>');
          $("#page2 ul li#item_"+cid).data('short', short_txt);
          
      }
      
      if (active_section==category) counter++;
      
    });
    
    
  }

  function setupEvents(){
    
    //main pagination
    
    var counts = 0;
    $(data_news).find('post').each(function(){  
        var $post = $(this);  
        var category = $post.find("category").text();
        if (active_section==category) counts++;
    });
    var pages = parseInt(counts/9);
    
    if (counts%9>0) pages++;
    
    pages = (pages<1)? 1 : pages;
    
    if (counts>9 && curr_page<pages) $("#flecha_der").fadeIn(); else $("#flecha_der").fadeOut();
    if (curr_page>1) $("#flecha_izq").fadeIn(); else $("#flecha_izq").fadeOut();
        
    $("#flecha_der, #flecha_izq").unbind(myEventClick).bind(myEventClick, function(){
    
          if ((curr_page==1 && $(this).attr('id')=='flecha_izq') || (curr_page==pages && $(this).attr('id')=='flecha_der')) return;
          
          if (animacion_paginando) return;
          animacion_paginando=true;
          
          var incrementador = 0;
    
          var init_pos = (curr_page-1)*9;
          var end_pos  = init_pos+9;
          
          if ($(this).attr('id')=='flecha_der') {
            var next_page_init_pos = end_pos;
            var next_page_end_pos  = end_pos+9;
          }
          else{
            var next_page_init_pos = init_pos-9;
            var next_page_end_pos  = init_pos;
          }
           
          $("#page2").html('<ul></ul>');
       
          var counter=0;
          var $startCategory = $(data_news).find('post:eq(0)');
          var tempCat = $startCategory.find('category').text();
          
          $(data_news).find('post').each(function(){  

            var $post = $(this);  
            var title = $post.find("title").text();
            var short_title = $post.find("short_title").text();
            var short_txt = $post.find("short").text();
            var image = $post.find("image").text();
            var category = $post.find("category").text();
            var link = $post.find("link").text();
            
            //if (category!=tempCat) { counter=0;tempCat = category;}
      
            var cid = $post.find("id").text();;
                      
            //armar página siguiente
            if (counter>=next_page_init_pos && counter<next_page_end_pos && active_section==category){
                $("#page2 ul").append('<li id="item_'+cid+'" title="'+title+'"><a href="'+link+'" style="background-image:url('+photos_path+"/"+image+');"></a></li>');
                
                $("#page2 ul li#item_"+cid).data('short', short_txt);
                
                
            }
            
            if (active_section==category) counter++;
            
          });
          
          
          
          if ($(this).attr('id')=='flecha_der') {
            curr_page++;
            direction = "-";
            direction2 = "+";
          }
          else {
            curr_page--;
            direction = "+";
            direction2 = "-";
          }
          
          History.replaceState({detalle:0}, globalSiteTitle + " " + active_section, "?"+active_section+"/"+curr_page); 
          
          curr_width = $("#page1").width()+100;
          
          if (counts<9 || curr_page==pages) $("#flecha_der").fadeOut();
          if (curr_page==1) $("#flecha_izq").fadeOut();
          
          $("#page1").animate({'margin-left': direction+"="+curr_width+"px"}, 500, 'swing', function(){
            //$(this).hide();
          });
          
          $("#page2 ul li").show();
          
          $("#page2").css('margin-left',direction2+curr_width+'px').animate({'margin-left': direction+"="+curr_width+"px"}, 500, 'swing', function(){
            
              //preparar página actual
              $("#page1").html($("#page2").html()).css({
                  'margin-left': $("#page2").css('margin-left')
              });
              
              setTimeout(function(){
                $("#page2").css('margin-left',''+curr_width+'px');
              }, 50);              
              
              //re armar páginas
              setupEvents();
              animacion_paginando=false;
              setTimeout(function(){
                $("#page2").css('margin-left','-99999px')
              }, 50);
              
          });
    
    });//click flechas
    
    

    //Wheel
    if (!isEventSupported('swipeleft')){
        $("body").unbind('mousewheel').bind('mousewheel', function(event, delta) {
              if (delta<0) $("#flecha_der").trigger(myEventClick);
              else $("#flecha_izq").trigger(myEventClick);
              return false;
        });
    }
    else{
         $("body").unbind('swipeleft').bind('swipeleft', function() {
              $("#flecha_izq").trigger(myEventClick);
              return false;
        });
        $("body").unbind('swiperight').bind('swiperight', function() {
              $("#flecha_der").trigger(myEventClick);
              return false;
        });
    }
    
    
    
    //click
    $("#page1 ul li").unbind(myEventClick).bind(myEventClick, function(){
        
        $(this).mouseleave();
        
        //traer datos dinámicos
        var cid = $(this).attr('id');
        
         //si es internal link, procesar
        var content_temp = $.trim(String(itemsDescriptions[cid]));
        content_temp = content_temp.substr(0,content_temp.length-5);
        
        
        var isInternal = content_temp.substr(0,12);
        
        if (isInternal=='<p>[internal'){
          var temp_str = content_temp.split('?');
          var $new_url = temp_str[1].split('/');
          
          var item = $new_url[3].split('&')[0];
          var section = $new_url[0];
          var page = $new_url[1];
          
          viewItem(item, section, page);
          
          return false;
        }
        
        
        
        viendoFicha=true;
        
        //disable main wheel
        $("body").unbind('mousewheel');
        
        
        
        
        //titulo
        $("#ficha h3").html($(this).attr('title'));
        
        History.replaceState({detalle:cid}, $(this).attr('title'), "?"+active_section+"/"+curr_page+"/detalle/"+cid); 
        
        //texto
        var content = itemsDescriptions[cid];
        
        if ($("#bio_contentwrapper").html()==null) $("#bio").html(content);
        else $("#bio_contentwrapper").html(content);
        fleXenv.updateScrollBars();
        
        prepareInternalLinks();
        
        //foto
        if (active_section!='work'){
            var arch = $('a:eq(0)',this).css('background-image');
            var arch_orig = arch;
            var partes = arch.split('/');
            var file = partes[partes.length-1];
            var arch = file.substring(0, file.length-2);
            if ($.browser.webkit) arch = file.substring(0, file.length-1);
            $("#bio_pic").css('background-image', arch_orig).show();
            
        }
        else{
            $("#bio_pic").hide();
        }
        
                       
        //obscurecer los otros items
        $("#cover").css({height:$("#page1").height()}).fadeTo(600, 0.4).unbind(myEventClick).bind(myEventClick, function(){
          $("#close").trigger(myEventClick);
        });
        
       
        //esconder las flechas
        $("#flecha_izq").attr('estabaVisible', $("#flecha_izq").css('display'));
        $("#flecha_der").attr('estabaVisible', $("#flecha_der").css('display'));
        $("#flecha_izq, #flecha_der").fadeOut();
        

        var nl = parseInt($(".default_page ul li:eq(0)").width());
        
        //a que posición corresponde, izq o der?
        var newcid = parseInt(cid)+1;
        fichaGlobalPos = 'izq';
        posOut = ((nl*3)+60)*-1;
        posIn = 0;
       
        if ((newcid%3==2) || (newcid%3==0)) { 
          fichaGlobalPos ='der';
          posOut = ((nl*3)+60);
          posIn = nl;
        }
              
        $("#ficha").stop().css({
            'left':posOut+'px'
        }).show().animate({
          'left' : posIn+"px"
          }, 1600, 'easeOutQuint');
          $("#close").fadeIn(function(){
          
            setClosePosition();
            
            if ($.browser.msie) $("#close").show();
          
            if (primeraVezFicha) {
        
            var tmpint = setTimeout(function(){
                $("#close").effect('shake', { times:3, direction: 'up' }, 100);
            }, 1000);
            
            primeraVezFicha=false;
          
            }
          });
          setupFichaScroll();
          
          setTimeout(setupFichaScroll, 100);
          setTimeout(setupFichaScroll, 500);
          
         return false;
    });
    
   $("#close").unbind(myEventClick).bind(myEventClick, function(){
      
        //restaurar main wheel
        $("body").bind('mousewheel', function(event, delta) {
          if (delta<0) $("#flecha_der").trigger(myEventClick);
          else $("#flecha_izq").trigger(myEventClick);
          return false;
        });
        
        //restaurar history
        History.replaceState({detalle:0}, globalSiteTitle + " - " + active_section, "?"+active_section+"/"+curr_page); 
        
        //restaurar los otros items
        $("#cover").fadeTo(400, 0, function(){ $(this).hide();});

        //restaurar las flechas
        if ($("#flecha_izq").attr('estabaVisible')=='block') $("#flecha_izq").fadeIn();
        if ($("#flecha_der").attr('estabaVisible')=='block') $("#flecha_der").fadeIn();
        
        var nl = parseInt($(".default_page ul li:eq(0)").width());
        posOut = ((nl*3)+60)*-1;
        posIn = 0;
        
        if (fichaGlobalPos=='der') { 
            posOut = ((nl*3)+60);
            posIn = nl;
        }
        
        $("#ficha").animate({
          'left' : posOut+"px"
          }, 1600, 'easeOutQuint', function(){viendoFicha=false;});
        
        $("#close").fadeOut();
      
   });
   
   setupFichaScroll();
    

  }
  
  function setupFichaScroll(){
     
     //scroll
      var itemHeight = $(".default_page ul li:eq(0)").height();
      
      var bioHeight = parseInt($(".default_page ul li:eq(0)").height()*3) - parseInt(itemHeight) - parseInt($("#ficha h3").height()) - 20;
      
      if (active_section=='work') bioHeight = parseInt($(".default_page ul li:eq(0)").height()*3) - parseInt($("#ficha h3").height()) - 20;      
      
      
      var bioWidth = ($(".default_page ul li:eq(0)").width()*2)-40;
            
      $("#bio").css('height',bioHeight+'px');
      $("#bio").css('width',bioWidth+'px');


      fleXenv.fleXcrollMain("bio");
      fleXenv.fleXcrollMain("intro_txt");
      
      
      setTimeout(function(){fleXenv.updateScrollBars();}, 200);
      setTimeout(function(){fleXenv.updateScrollBars();}, 500);
      setTimeout(function(){fleXenv.updateScrollBars();}, 1000);
      
      primeraVezScroll=false;
      
  }
  
  function fixFontSize(){
      //font-size
      var max = 68;
      var min = 10;
      
      var nw = $("body").width();
      var nh = $("body").height();
      
      var fs = (Math.ceil(nw * parseInt(40) / 600) );
      
      if (fs<min) fs = min;
      if (fs>max) fs = max;
      
      $(".default_page ul li div span").css('font-size', fs+ 'px');
      
      $(".title_suc").css('font-size', (fs*1.3)+ 'px');
      
      $("#col2 .row2").css('font-size', (fs*0.27)+ 'px');
      
      
      var h = $("#col1 .row1").height();
      if ((fs*2.2)>h) fs = h/2.2;
      if (fs>max) fs = max;
      $(".about_slogan").css('font-size', (fs*0.5)+ 'px');
      
      
  }
  
  function fixSlogan(){
        
        var temp_h = $(".logo_azul img").width();
        temp_h = temp_h / 4;
        $(".logo_azul img").css('height', temp_h+'px');
  }
  
  function drawInterfase(){
  
      var new_img_height = ( $("body").height() - 90 ) / 3;
      var pageHeight = $("#page1").height();
      var itemHeight = $(".default_page ul li:eq(0)").height();
      
      if ($.browser.webkit) {
          
          //$(".default_page ul li a").css('height', (new_img_height+20)+'px');
      }
      
      $(".default_page ul li, #bio_pic").css('height', new_img_height+'px');
      
      $("#ficha").css('height',(new_img_height*3)+'px');
      
      var bioHeight = parseInt(new_img_height*3) - parseInt(itemHeight) - parseInt($("#ficha h3").height()) - 20;
      if (active_section=='work') bioHeight = parseInt($(".default_page ul li:eq(0)").height()*3) - parseInt($("#ficha h3").height()) - 20;      
      
      
      $("#bio").css('height',bioHeight+'px');
      
      $("#cover").css({'height':pageHeight+'px'});
      
      
  }
  
  
  
  $(window).resize(function(){
  
   fixFontSize()
   setupFichaScroll();
   
   //var nl = parseInt($(".default_page ul li:eq(0)").width());
   var nl = parseInt($("body").width());
  
   if (viendoFicha){

        posOut = 0;
       
        if (fichaGlobalPos=='der') { 
           
          posOut = nl;
        }
        $("#ficha").stop().css({
            'left':posOut+'px'
        });
      
   }
   else{
      
      $("#ficha").stop().css('left',((nl)+60)+'px');
   }


    setTimeout(function(){setClosePosition();}, 100);
    setTimeout(function(){setClosePosition();}, 300);
    
    var pageHeight = ( $("body").height() - 90 );
    
    $("#contact").css({'height':pageHeight+'px'});
    $("#about").css({'height':pageHeight+'px'});

   
    //fix circus in about - all because of chrome
    var temp_h = $(".logo_azul img").width();
    temp_h = temp_h / 4;
    $(".logo_azul img").css('height', temp_h+'px');
   
  
  });
  
  if ( window.orientation != undefined )  window.onorientationchange = updateViewOrientation();
  
  function updateViewOrientation(){
    $(window).resize();
  }
  
  function setClosePosition(){
    var closeTop = parseInt($("#bio_pic").height()) + 10;       
    if (active_section=='work') closeTop = "35";
       
      $("#close").css({
        'top':closeTop+'px'
        
      });
  }
  
  function debug(text){
    console.log(text);
    $("nav").html(text);
  }
  
  function loadXML(xml){
      
      var images = [];
      
      $.get(globalXMLFile+ "?" + new Date().getTime(), function(d){  
          
          data_news = d;
          var counter =0 ;
          var counter2 =0 ;
          $(d).find('post').each(function(){  
  
            var $post = $(this);  
            var title = $post.find("title").text();
            var short_title = $post.find("short_title").text();
            var short_txt = $post.find("short").text();
            var image = $post.find("image").text();
            var category = $post.find("category").text();
            var link = $post.find("link").text();
            var cid = $post.find("id").text();
            
            if (active_section==category) {
                
                $("#page1 ul").append('<li id="item_'+cid+'" title="'+title+'"><a href="'+link+'" style="background-image:url('+photos_path+"/"+image+');"></a></li>');
                
                $("#page1 ul li#item_"+cid).data('short', short_txt);
            }
            
            
            if (counter2<10&&active_section==category) {
              images.push(photos_path+"/"+image);
              counter2++;  
            }
            else globalImagesArray.push(photos_path+"/"+image);
            
            itemsDescriptions["item_"+cid] = short_txt;
            
            counter++;
          });

          $(images).preloadImages(function(){ 
          
            
          
            $(globalImagesArray).preloadImages();          
            
          }); 
          
          setTimeout(setupAfterDataReady, 1400);         


          
      }).error(function() { alert("error xml");});
      
      
    }
  
 
  // Helper function, used below.
  // Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
  Array.prototype.remove = function(element) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == element) { this.splice(i,1); }
    }
  };

  // Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
  // Callback function gets called after all images are preloaded
  $.fn.preloadImages = function(callback) {
    checklist = this.toArray();
    this.each(function() {
      var imagen = this+ "?" + new Date().getTime();
      $('<img>').attr({ src: imagen, tmpsrc : this }).load(function() {
        checklist.remove($(this).attr('tmpsrc'));
        if (checklist.length == 0) { 
         var isFunc = jQuery.isFunction(callback);
         if (isFunc) callback(); 
         }
      });
    });
  };
  

  function getUrlVars()
  {
      var vars = [], hash;
      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++)
      {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
      }
      return vars;
  }
  
  function isIOS(){
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    return agentID;
  }
  


  
});




