// globals
var default_css = {
      'background-color' : 'transparent'
      }

var selected_css = {
      'background-color' : '#ebf0f2'
      }

var hidden_css = {
      'display' : 'none'
      }




var Omni = function(){ }
Omni.sitemap = {
    cache:'',
    opened:false,
    animating:false,
    open:function(){
        if(Omni.sitemap.cache == ''){
            $.ajax({ type: "POST", url: "/sitemap/?ajax=true",
                success:function(response){
                    Omni.sitemap.cache = response;
                    $('#map .wrp').html(Omni.sitemap.cache);
                    Omni.sitemap.post_open()
                }
            })
        } 
        else Omni.sitemap.post_open();
    },
    post_open:function(){
        Omni.sitemap.animating = true;         
        $('#map').fadeIn('fast');
        $('#openmap').removeClass('downarrow')
        $('#openmap').addClass('uparrow')
        var targetOffset = $('#footer').offset().top
        $('html,body').animate({scrollTop: targetOffset}, 1000, function(){
            Omni.sitemap.animating = false;         
        });
        Omni.sitemap.opened = true;
    },
    close:function() {
        if(Omni.sitemap.opened){
            $('#openmap').removeClass('uparrow')
            $('#openmap').addClass('downarrow')
            var targetOffset = $('.home').offset().top
            $('html,body').animate({scrollTop: targetOffset}, 1000, function(){
                $('#map').fadeOut('fast');
            });
            Omni.sitemap.opened = false;
        }
    }
    
}

ClientLove = function(){ 
    this.init();
}

ClientLove.prototype = {
    base_url:'',
    pos:0,
    cache:[],
    container:{},
    next_button:{},
    prev_button:{},
    
    change:function(){

        this.container.hide();

        var obj = this.cache['tests'][this.pos];
        var proj = {};

        for(var i = 0 ; i < this.cache['projects'].length ; i++) {
            if( this.cache['projects'][i].pk == obj.fields.project ) 
            {
               proj = this.cache['projects'][i].fields;  
               //console.log(this.cache['projects'][i].pk + ' ' + obj.fields.project + ' ' + proj);
               break;
            }
        }

        var cite = $('#cl_cite');
        var quote = $('#cl_quote');
        var strap = $('#casestudyStrap');
        var url = $('#cl_url');

        url.attr('href', proj.url);

        cite.html(obj.fields.cite + ', ' + obj.fields.position + ', ' + obj.fields.company);
        quote.html(obj.fields.quote); 

        var so = new SWFObject('/site_media/swf/casestudy_strapline.swf', "readme", '508', '80', "10", "#ffffff");
        so.addParam("wmode", "transparent");
        so.addVariable("title", proj.title);
        so.addVariable("subtitle", proj.strap);
        so.write("casestudyStrap");

        this.container.fadeIn('fast');

        window.location.href = this.base_url + '#' + obj.pk;

        if(this.pos-1<0)
          this.next_button.attr('href', this.cache['tests'][this.cache['tests'].length-1].fields.url);         
        else
          this.next_button.attr('href', this.cache['tests'][this.pos-1].fields.url);



        if(this.pos+1>=this.cache['tests'].length)
          this.prev_button.attr('href', this.cache['tests'][0].fields.url)
        else
          this.prev_button.attr('href', this.cache['tests'][this.pos+1].fields.url)



        // Hide buttons
        console.log('Position ' + this.pos);
        console.log('length ' + this.cache['tests'].length);
        if(this.pos == this.cache['tests'].length-1) 
        {
            //this.next_button.fadeOut();
            this.next_button.css('opacity', '.2');
        }
        else if(this.pos == 0)
        {
            //this.prev_button.fadeOut();
            this.prev_button.css('opacity', '.2');
        }
        else
        {
            this.next_button.css('opacity', '1');
            this.prev_button.css('opacity', '1');
        }

    },

    next:function(){
        if(this.pos < this.cache['tests'].length-1){
            this.pos++;
            this.change();
        }
        else
        {
          this.pos = 0
          this.change();
        }


    },
    prev:function(){
        if(this.pos > 0) {
            this.pos--;
            this.change();
        }
        else
        {
          this.pos = this.cache['tests'].length-1
          this.change();
        }
    },

    init:function(){
        this.base_url = String(window.location.href).split('#')[0];
        this.container = $('#lovecontainer');
        var me = this;
        $.getJSON("/client-love/json",
            function(data){
                me.cache = data;
                me.setup_buttons();
            }
        );

    },

    setup_buttons:function(){
        var me = this;
        this.next_button = $('#lovecontroller a.right');
        this.prev_button = $('#lovecontroller a.left');
        this.next_button.click(function(){
            me.next();
            this.blur();
            return false;
        })
        this.prev_button.click(function(){
            me.prev();
            this.blur();
            return false;
        })

    }

}













PortFolioItem = function(){ 
    this.init();
}

PortFolioItem.prototype = { 

  init: function() {

    var t = this;
  
    // SIDE NAVIGATION 
    if($('ul.portfolio li').length>0)
    {
      $('ul.portfolio li').each(function() {

    		$(this).mouseover(function() {
    			$(this).addClass('selected');
    			var project = $(this.firstChild).attr('rel');
    			$('#'+project).addClass('border');
    		});
                  /*
        $(this).click(function() {
          //t.fetch($(this.firstChild).attr('rel'));
          t.decorate($(this.firstChild).attr('rel'));

          return false;
        });
                  */
    		$(this).mouseout(function() {
    			$(this).removeClass('selected');
    			var project = $(this.firstChild).attr('rel');
    			$('#'+project).removeClass('border');
    		});
      });
    }

    // OVERVIEW PAGE HAS GRID OF LOGOS 
    if($('.mirror').length>0)
    {
    	$('.mirror').each(function() {
    		$(this).mouseover(function() {
    			$(this).addClass('border')
    			var menuselector = $(this).attr('id')
    			$('[rel='+menuselector+']').parent().addClass('selected')
    		});
            /*
        $(this).click(function() {
          t.decorate($(this).attr('id'));
          return false;
        });
            */
      	$(this).mouseout(function() {
    			$(this).removeClass('border')
    			var menuselector = $(this).attr('id')
    			$('[rel='+menuselector+']').parent().removeClass('selected')
        });
      });
    }

  },

  fetch: function(projectID){ 
	//
    var t = this;
    $.ajax({
        type: "GET",
        url: "/our-work-request/more",
        data: "p="+projectID,
        success: function(response){
			
          // restore any navigation selected states to normal
          $('ul.subpages a').each(function() {
            $(this).parent().css(default_css);
          })
			  
          // add the new selected state
          $('a[rel='+projectID+']').parent().css(selected_css);
		  
          // and add the new content 
          $('#view').html(response);

          var so = new SWFObject('/site_media/swf/h1header.swf', "pageTitle", '508', '50', "10", "#ffffff");
          so.addParam("wmode", "transparent");
          // grab replacement txt from the h1's inner HTML
          var title = $('#view #projecttitle').html().toLowerCase().split('<br>')[0]
          var subtitle = $('#view #projecttitle').html().toLowerCase().split('<br>')[1]

          if(title && subtitle)
          {
            so.addVariable("title", title.replace('&amp', '%26'));
            so.addVariable("subtitle", subtitle.replace('&amp', '%26'));
            so.write("projecttitle")
          }

          $('#view').fadeIn();
          // for functionality and presentation
          t.execute(projectID)

        }
    })
  },

  decorate: function(projectID) {
    
      //  This makes a JSON request to get the project's large decroative image
    
	
    var t = this
  	// Assume default browser title
    document.title = 'Our Work' 
    // Remove current direction
    $('#decoration').fadeOut('fast');
  	// Hide content
    $('#view').html('')
    $('#view').hide()
	
    //  get URL
    $.getJSON("/our-work-request/more", { vurl:projectID }, function(ajaxurl){
      window.location.hash = ajaxurl.url     
    });


    //  get expanding page decoration image
    $.getJSON("/our-work-request/more", { vpk:projectID }, function(myproject){
        // for unique browser title  
        if(myproject.browser && myproject.browser != '')
        {
          document.title = myproject.browser
        }
        var projectBg_css = {
          'background-image':'url(/site_media/' + myproject.decoration +')',
          'background-repeat':'none'
        };

        $('#decoration').css('background-image', 'url(/site_media/' + myproject.decoration +')')
        $('#decoration').css('background-repeat', 'none')
        $('#decoration').fadeIn()
    });
    // get content
    t.fetch(projectID);

  },

  execute: function() {
	
	  //  This puts event behaviour on links from an indivudal project's
	//	view to it's related projects
	
	  
    var t = this

    if($('.project').length>0)
    {
      $('.project').each(function() {
        $(this).mouseover(function() {
          $(this).addClass('border')
          
        });
        /*
        $(this).click(function() {
          t.decorate($(this).attr('id'));
          return false;
        });
        */
        $(this).mouseout(function() {
          $(this).removeClass('border')
        })
      });
    }

  }
  
   

};































$(document).ready(function() {
	
  $('#view').hide()
	  

 

  /* PORFTOLIO PAGE CHECKS */
  
  // check what it is the addressbar
  var url = new String(window.location)
  // New portfolio IFF no HTTP requests have interferred with the address already, else they willmake no sense
  var casestudyHTTP_url = /[a-z]*\/our-work\/$/;
  var matchPos1 = url.search(casestudyHTTP_url);
  
  if($('.portfolio').length>0 && matchPos1!=-1)
  {
    portfolio = new PortFolioItem();
  }

  // then check if we have a returning JS user to the CASESTUDY page, i.e. # trailing our-work/
  
  
  //var casestudyJS_url = /our-work\/#+[a-z]*/;
  
  /*
  
  
  var matchPos2 = url.search(casestudyJS_url);
  
  if(matchPos2 > 0)
  {
  	url = url.split('#',2)[1]
    portfolio = new PortFolioItem();
    portfolio.decorate(url.split('/',2)[1])
  }

  else   // THIS IS TO TRANSFORM THE BLOG PAGE FROM IT'S DEFAULT NON-JS LAYOUT TO THE MORE FANCY J-QUERY PAG
  {
    
    if($('div.blogbuttons').length>0)
    {
      $('.comment').each(function(){
        $(this).css('display', 'none');
      });
      $('div.blogbuttons').each(function(){
        $(this).css('display', 'block');
      });
      $('div.commentform').each(function(){
        $(this).css('display', 'none');
      });
    }
    

    // now a few other improvements 
    if($('#lovecontroller').length>0)
    {
      $('#lovecontroller').css('display','none')
      $('#lovecontroller').fadeIn(2000)
    }



  }
  
  
  
  */
  
  
  
  if($('div.blogbuttons').length>0)
    {
      $('.comment').each(function(){
        $(this).css('display', 'none');
      });
      $('div.blogbuttons').each(function(){
        $(this).css('display', 'block');
      });
      $('div.commentform').each(function(){
        $(this).css('display', 'none');
      });
    }
    

    /* now a few other improvements */
    if($('#lovecontroller').length>0)
    {
      $('#lovecontroller').css('display','none')
      $('#lovecontroller').fadeIn(2000)
    }
  


  $('#view').fadeIn()


  /* site map */
	$('#openmap').click(function() {
        if(!Omni.sitemap.opened)
        {
            Omni.sitemap.open();
        }
        else
        {
            Omni.sitemap.close();
        }
        return false;
    });




  /* blog */
  $('a.openall').each(function() {       


    $(this).toggle(
      function() {    
    
        //  select only the comments and links that are within the correct container
        var idstring = $(this).parent().parent().attr('id')

        $('#'+idstring+' a.openall').text('Close Comments');

        var allcomments = $('#'+idstring+' div.comment');

        var c = 0;
        for(var i=0; i<allcomments.length; i++)
        {
          var t = c;
          delay_fade($(allcomments[i]), 50*t);
          c++;
        }

        return false
      },


      function() {

        var idstring = $(this).parent().parent().attr('id')
        $('#'+idstring+' a.openall').text('View Comments');
        var allcomments = $('#'+idstring+' div.comment');

        for(var i =0; i<allcomments.length; i++)
        {
          $(allcomments[i]).fadeOut('fast');
        }

        return false;
      }
    );	



  });


  /* open comment form */
  $('a.add').each(function() {       
    $(this).toggle(		
      function() {   
        //  select only the comments and links that are within the correct container
        var idstring = $(this).parent().parent().attr('id')
        $('#'+idstring+' .commentform').slideDown('15000')    
        $(this).text('Hide');
        return false
      }
      ,function() { 
        //  select only the comments and links that are within the correct container
        var idstring = $(this).parent().parent().attr('id')
        var link = $(this)
        $('#'+idstring+' .commentform').slideUp('1000', function() { link.text('Leave Comment') });
        return false
      }
    );
  });


    

}); 