

var startPage = 'blog';
//var startPage = 'about';
//var startPage = 'skills';


$(document).ready(function($){
   $.preloadCssImages({
      statusTextEl: '#textStatus', 
      statusBarEl: '#status'
   });
   $(window.parent.document).find('iframe:eq(0)').height('110em');
   

});
/*
 (function() {
    var ga = document.createElement('script');ga.type = 'text/javascript';ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(ga, s);
  })();
  */

function loadContent(page)
{
   $('#loadingBox').show();
   $('#loadingPic_top').show();
   
   if(page=='')
      page = startPage;
      
   if(page=='cv')
      document.title = "Elmered.com - Curiculum Vitae";      
   else if(page=='about')
      document.title = "Elmered.com - About Peter";      
   else
      document.title = "Elmered.com - "+page.slice(0,1).toUpperCase() + page.slice(1);
   
   var ajaxurl;
   var headerText;
   
   $("#nav > li").removeClass('navigationActive');
   $("#projectsNav > li").removeClass('navigationActive');
   
   if(page.indexOf('portfolio/')==0)
   {
      var page_split = page.split("/");
      ajaxurl = 'pages/'+page_split[0]+'.php?p='+page_split[1];

      headerText = pages[page_split[0]]+": "+portfolio[page];
      page = page_split[0];
      
      $('#menu_'+page+'-'+page_split[1]).parent('li').addClass( 'navigationActive');
   }
   else
   {
      ajaxurl = 'pages/'+page+'.php';
      headerText = pages[page];
   }
   
   $('#menu_'+page).parent('li').addClass( 'navigationActive');
   
   $.ajax({
      url: ajaxurl,
      success: function(data) {

         $('#testcontent').html(data);
       
         var contentHeight = $('#testcontent').height();
         $('#testcontent').html('');
       
         if(contentHeight < 500)
            contentHeight = 500;
         
         //alert(contentHeight);

         $('#content').stop().animate(
         {
            height: contentHeight
         }, 1000, 
         function()
         {
            //$('#content').fadeTo(100, 1);
            //$('#content').hide(0, function() {
               $('#content').hide().html(data)
               $('#topHeaderText').hide().html(headerText).fadeTo(900, 100);
               $('#loadingPic_top').hide();
               $('#content').fadeTo(900, 100);
               $('#loadingBox').hide();
               initPage(page);
            //});
         });
         
         //Google analytics tracking
         //pageTracker._trackPageview("/"+page );
         
         pageTracker._trackPageview("/"+page );

      },
      error : function (xhr, d, e)
      {
         if (xhr.status == 404)
         {
             $('#content').stop().animate(
            {
               height: 500
            }, 1000, 
            function()
            {
               //alert('404: Sidan kunde inte hittas!');
               $('#topHeaderText').hide().html('404: Not found');
               $('#content').hide().html("<h1>Oops!</h1> Sidan kunde inte hittas :(").fadeIn();
               $('#topHeaderText').html("404: Not found").fadeTo(900, 100);
               $('#loadingPic_top').hide();
               $('#loadingBox').hide();
            });
         }
         else
         {
            alert('Okänt fel!');
         }
         $('#loadingBox').hide();
      }
   });
}

function initBars()
{
   var i = 1;
   while($("#bar"+i).length != 0)
   {
      var title = $("#bar"+i).attr("title"); 
      $("#bar"+i).progressBar(0);

      if(title != "")
      {
         $("#bar"+i).progressBar({
            max: title, 
            textFormat: 'hp',
            barImage: 'pics/progressbg_green.gif'
         } );
      }
      else
         $("#bar"+i).progressBar($("#bar"+i).html(), {
            barImage: 'pics/progressbg_green.gif'
         });
alert($("#bar"+i).html());
      i++;
   }
}

function initPage(page)
{
   var i = 1;
   while($("#bar"+i).length != 0)
   {
      var title = $("#bar"+i).attr("title"); 

      if(title != "")
      {
         $("#bar"+i).progressBar({
            max: title, 
            textFormat: 'hp',
            barImage: 'pics/progressbg_green.gif'
         } );
      }
      else
         $("#bar"+i).progressBar( {
            barImage: 'pics/progressbg_green.gif'
         });

      i++;
   }
   /*
   var _gaq = _gaq || [];
   _gaq.push(
      ['_setAccount', 'UA-2535379-1'],
      ['_trackPageview', "/"+page]
      );
*/


   
   //$('#menu_ref').hide();
   
}
function initSite()
{
   var url = window.location.hash;
   url= url.replace(/^#/g, '');
   
   setTimeout(function() 
   {
      $('#body').fadeOut(500,function() {
         $.ajax({
            url: 'pages/page.php',
            success: function(data) 
            {
               $('#body').html(data);
               if(url)
               {
                  loadContent(url);
               }
               else
               {
                  //Ladda Statstida
                  loadContent(startPage);
               }
               getEPost();
               $('#body').fadeIn();
               
               //Twitter Widget
               new TWTR.Widget({
                  version: 2,
                  id: 'twitterBox',
                  type: 'profile',
                  rpp: 5,
                  interval: 6000,
                  width: 250,
                  height: 300,
                  footer: "Min profil",
                  theme: {
                     shell: {
                        background: '#333333',
                        color: '#ffffff'
                     },
                     tweets: {
                        background: '#000000',
                        color: '#ffffff',
                        links: '#4aed05'
                     }
                  },
                  features: {
                     scrollbar: false,
                     loop: false,
                     live: false,
                     hashtags: true,
                     timestamp: true,
                     avatars: false,
                     behavior: 'all'
                  }
               }).render().setUser('pelmered').start();
  
               $('#sidebar_left').find('li').hover(function(){
                  //alert('fa');
                  $(this).addClass('navigationHover');
               }
               , function(){
                  $(this).removeClass('navigationHover');
               })               
            }
         });
      });
   }, 200);
}

function getEPost( )
{
   var a = 'p&#101;t'+'&#101;r';
   var prefix = 'm&#97;&#105;lt&#111;:';
   var attribs = ' alt=\'Ma&#105;la ' + a + '\' ';
   var path = 'hr' + 'ef' + '=';
   var adress = a + '&#64;&#101;'+'lm&#101;r'+'&#101;d.&#99;'+'&#111;&#109;';

   $('#mail').html('<' + 'a ' + path + '\'' + prefix + adress + '\'' + attribs + '><img src="/pics/email.gif" alt="Email"/><\/a>' + '');
}
 
(function($) {
   var cache = [];
   // Arguments are image paths relative to the current page.
   $.preLoadImages = function() {
      var args_len = arguments.length;
      for (var i = args_len; i--;) {
         var cacheImage = document.createElement('img');
         cacheImage.src = arguments[i];
         cache.push(cacheImage);
      }
   }
})(jQuery)


function sendMail()
{
   $('#loadingBox').show();
   var paramstr = "";
 
   var submit = true;
 
   $('#mailForm :input').each(function()
   {
      paramstr =  paramstr + this.name+"="+this.value+"&";
      
      
      if(this.value == '')
      {
         if(this.name == 'name_')
         {
            alert('Du måste fylla i namn');
            submit = false;
         }
         else if(this.name == 'mailtext')
         {
            alert('Du måste fylla i meddelande');
            submit = false;
         }
      }
      if(this.name == 'epost')
      {
         var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
         if (!filter.test(this.value) || this.value == '')
         {
            alert('Du måste fylla i en korrekt e-postadress!');
            submit = false;
         }
      }
      
   });
   if(submit === false)
   {
      $('#loadingBox').hide();
      return false;
   }
   
   $.ajax({
      type: "POST",
      url: 'ajax/actionContact.php',
      data: paramstr,
      success: function(data) 
      {
         $('#contact').html(data);
      }
   });
   $('#loadingBox').hide();
   return true;
}


var elem;
function openEditor(e)
{
   elem = e;
   showPopup(elem, "contactMsg");
   document.getElementById('edtorText').value = elem.value;
   document.getElementById('edtorText').focus();
}

function closeEditor()
{
   elem.value = document.getElementById('edtorText').value;
   closePopup();
      
}
//Popupruta
function showPopup(id, type)
{
   document.getElementById('popupBackground').style.display = 'block';
   document.getElementById('popupBackground').setAttribute('onclick', 'javascript:closeEditor();');
   document.getElementById('popupBox').style.display = 'block';
   url = "/ajax/info.php?action="+type+"&id="+id;
   if(type == "contactMsg")
   {
      document.getElementById('popupBox').innerHTML = "<a class='closelink' onclick='javascript:closeEditor()'>Spara och stäng</a><div class='info_popupcontainer'><h3>Skriv meddelande:</h3><textarea id='edtorText'>"+
      id.innerHTML+
      "</textarea>Klicka \"Spara och stäng\", Ctrl+enter eller utanför rutan för att spara och stänga.</div><a class='closelink_bottom' onclick='javascript:closeEditor()'>Spara och stäng</a>";
         
      var isCtrl = false;
      document.onkeyup=function(e)
      {
         if(e.which == 17)
            isCtrl=false;
      }
      document.onkeydown=function(e)
      {
         //Check if ctrl is pressed
         if(e.which == 17)
            isCtrl=true;
         //Check for CTRL+ENTER
         if(e.which == 13 && isCtrl == true)
         {
            closeEditor();
            return false;
         }
      }
   }
}

function closePopup()
{
   document.getElementById('popupBox').style.display = 'none';
   document.getElementById('popupBackground').style.display = 'none';
}

