/*

	13twelve vs. Jim Neath vs. Lofty vs. jQuery

	This javascript is the main javascript for the sites actions.
	
*/

// --------------------------------------------------------------------------------------------------------------
// set up variables

var isSafari = false;
var isSafari3 = false;
var isSafari4 = false;
var isIE = false;
var isIE6 = false;
var isIE7 = false;
var isIE8 = false;
var isMozilla = false;
var isOpera = false;
var isMac = false;
var isiphone = false;

// --------------------------------------------------------------------------------------------------------------
// what to do on DOM ready
$(document).ready(function(){
	runOnDOMready();	
	$(window).load(function() {
		// what to do when body loaded
		runOnLoaded();
	});
});
// what to do when window scrolls
$(window).scroll(function () { onScrollFunction(); });
// what to do when window resizes
window.onresize = onResizeFunction;

// --------------------------------------------------------------------------------------------------------------

function runOnDOMready() {	
	// sitewide functions	
	
	//if (window.console && isMozilla) { console.time("browserTest"); }
	browserTest();
	//if (window.console && isMozilla) { console.timeEnd("browserTest"); }	
	
	//if (window.console && isMozilla) { console.time("setUpClasses"); }
	setUpClasses();
	//if (window.console && isMozilla) { console.timeEnd("setUpClasses"); }
	
	// sliders
	siteSliders();
	
	// our studio/homepage alternate images
	// ourStudioImages();
	
	setInterval( "slideSwitch()", 5000 );
	
	// swap team members
	team();

	// projects tile swap and lb launch
	projects();
	
	// news stories swap
	// news();
}

function runOnLoaded() {
}

function onResizeFunction() {
    // thin?
	if($(window).width() < 1200) {
	    $("body").addClass("thin");
	} else {
	   $("body").removeClass("thin"); 
	}
}

function onScrollFunction() {
}


// --------------------------------------------------------------------------------------------------------------
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ application wide functions */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (remember to test if the elements you are messing with exist) */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ( eg. if (($('body.homepage'))!=""){ } ) */

// this function search and replaces a string and returns the new string
// http://www.daveshuck.com/blog/index.cfm/2006/12/13/Javascript-examples--removeElement-and-replaceAll
function replaceAll( str, searchTerm, replaceWith, ignoreCase )   {
   var regex = "/"+searchTerm+"/g";
   if( ignoreCase ) regex += "i";
   return str.replace( eval(regex), replaceWith );
}

// @ppk cookies funcs
// http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

// image preloader
// http://warpspire.com/tipsresources/interface-scripting/image-preloading-revisited/
var Preloader = {
  callbacks: [],
  images: [],
  loadedImages: [],
  imagesLoaded: 0,

  add: function(image){
    if (typeof image == 'string') this.images.push(image);
    if (typeof image == 'array' || typeof image == 'object'){
      for (var i=0; i< image.length; i++){
        this.images.push(image[i]);
      }
    }
  },
  onFinish: function(func){
    if (typeof func == 'function') this.callbacks.push(func);
    if (typeof func == 'array' || typeof func == 'object'){
      for (var i=0; i< func.length; i++){
        this.callbacks.push(func[i]);
      }
    }
  },
  load: function(){
    for(var i=0; i<this.images.length; i++){
      this.loadedImages[i] = new Image();
      this.loadedImages[i].onload = function(){ Preloader.checkFinished.apply(Preloader) }
      this.loadedImages[i].src = this.images[i];
    }
  },

  checkFinished: function(){
    this.imagesLoaded++;
    if (this.imagesLoaded == this.images.length) this.fireFinish();
  },
  fireFinish: function(){
    for (var i=0; i<this.callbacks.length; i++){
      this.callbacks[i]();
    }
    this.images = [];
    this.loadedImages = [];
    this.imagesLoaded = 0;
    this.callbacks = [];
  }
}


function browserTest() {
	/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ some simple browser testing */
	// are we on a Mac ?
	if (navigator.appVersion.indexOf("Mac")!=-1) {
		isMac = true;
		$('body').addClass("isMac");
	} 
	function searchVersion(browser) {
		var dataString = navigator.userAgent;
		var index = dataString.indexOf(browser);
		if (index == -1) return;
		var bVersion = parseFloat(dataString.substring(index+browser.length+1));
		return bVersion.toString().split(".")[0];
	}
	
	// Safari versioning
	isSafari =  jQuery.browser.safari;
	if (isSafari) {	
		$('body').addClass("isSafari");
		version = searchVersion("Version") || + "";	
		$('body').addClass("isSafari"+version);
		isSafari3 = (version == 3) ? true : false;
		isSafari4 = (version == 4) ? true : false;
	}
		
	// IE versioning
	isIE = jQuery.browser.msie;
	if (isIE) {	
		//$('body').addClass("isIE");
		version = searchVersion("MSIE") || "";
		//$('body').addClass("isIE"+version);
		isIE6 = (version == 6) ? true : false;
		isIE7 = (version == 7) ? true : false;
		isIE8 = (version == 8) ? true : false;
	}
	
	// Mozilla versioning
	isMozilla = jQuery.browser.mozilla;
	if (isMozilla) {
		$('body').addClass("isMozilla");
		version = searchVersion("Firefox") || "";
		$('body').addClass("isMozilla"+version);
	}
	
	// Opera versioning
	isOpera =jQuery.browser.opera;
	if (isOpera) {
		$('body').addClass("isOpera");
	}
	
	// iPhone
	if (navigator.userAgent.indexOf("iPhone") != -1) {
		isiphone = true;
		$('body').addClass("isIphone");
	}
}


function setUpClasses() {
    //$('input[type=submit]').addClass("submit");
	//$('input[type=radio]').addClass("radio");
	//$('input[type=checkbox]').addClass("checkBox");
	//$('input[type=image]').addClass("image");
	//$('input[type=file]').addClass("file");	
	$('li:first-child').addClass("first");
	$('li:last-child').addClass("last");
	//$('li:nth-child(even), tr:nth-child(even)').addClass("even");	
	$("a[href^=http]").attr("target","_blank");
	// thin?
	if($(window).width() < 1200) {
	    $("body").addClass("thin");
	}
}


function team() {
   if($("#people") && $("#people-selector")) {
       $("#people-selector").find("li a").each(function (i) {
           $(this).click(function(e){
               e.preventDefault();
               $(this).parent().siblings().removeClass("current");
               $(this).parent().addClass("current");
               $("#people").find(".current").fadeOut(300, function(){
                   $("#people").find(".current").removeClass("current")
                   $("#people").find("li:eq("+i+")").fadeIn(300, function(){
                      $("#people").find("li:eq("+i+")").addClass("current"); 
                   });
               });
           });
        });
   }
}

// MO 231109 remove random images, add slideshow
// function ourStudioImages() {
//  if($("#studio")) {
//    var img = $("#alt");
//    var rand = Math.floor(Math.random() * 8);
//    img.attr("src", "images/our-studio/" + rand + ".jpg");
//    img.css("display", "block");
//  }
// }

/*** 
    Simple jQuery Slideshow Script
    Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify, not responsible for anything, etc.  Please link out to me if you like it :)
***/

function slideSwitch() {
  
    var $active = $('#slideshow img.active');

    if ( $active.length == 0 ) $active = $('#slideshow img:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next() : $('#slideshow img:first');

    // uncomment the 3 lines below to pull the images in random order
    
     var $sibs  = $active.siblings();
     var rndNum = Math.floor(Math.random() * $sibs.length );
     var $next  = $( $sibs[ rndNum ] );

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

function siteSliders() {
    if($("#content")) {
        // add the headings div
        var headingsDiv = "";
        $("#content").find("h2").each(function () {
            headingsDiv = headingsDiv + "<p class='headings'>" + $(this).html() + "</p>";
        });
        headingsDiv = headingsDiv.toLowerCase();
        headingsDiv = replaceAll(headingsDiv, "our", "");
        headingsDiv = replaceAll(headingsDiv, " ", "");
        headingsDiv = replaceAll(headingsDiv, "pc", "p c");
        headingsDivAlt = '<div id="headingsAlt">' + headingsDiv + '</div>';
        headingsDiv = '<div id="headings">' + headingsDiv + '</div>';
        $("#content").prepend(headingsDiv);
        $("#content").before(headingsDivAlt);
        $("#headings").css({
                    position: "absolute", 
                    left: "0px", 
                    top: "0px",
                    width: "300px"
                }); 
                $("#headingsAlt").css({
                    position: "absolute", 
                    left: "242px", 
                    top: "99px"
                });
                
        // MO 231109
        $("#headings p:first-child").fadeIn("slow");
         Cufon.replace("#headings p:first-child");
        // EOF
        
        // set up sliders
        var x = 768 + 40; // article width + any margins, the horizontal slide distance
        var y = 478 + 70; // distance between headings, the vertical slide distance
        var y2 = 478 + 70; // distance between headings, the vertical slide distance
        var xMove = $('#articles'); // what to move horizontally
        // var yMove = $('#headings'); // what to move vertically
        var y2Move = $('#headingsAlt'); // what to move vertically
        var xProperty = "left"; // which css property to move
        var yProperty = "top";
        var y2Property = "top";
        var xInit = 0; // initial move
        var yInit = 0;
        var y2Init = 99;
        var speed = 700; // smooth lol
        var easing = "swing";
        var sliding = false; // flag to stop multiple clicks
        // movement calcs
        function xNextPos(i) {
            var pos = xInit - (i * x);
            return pos
        }
        function yNextPos(i) {
            var pos = yInit - (i * y);
            return pos
        }
        function y2NextPos(i) {
            var pos = y2Init - (i * y2);
            return pos
        }
        // movement
        function slide(i) {
            if (!sliding) {
                Cufon.replace('p.headings');
                $("nav").find(".current").removeClass("current");
                $("nav").find("li:eq("+i+")").addClass("current");
                //
                sliding = true;
                // yMove.css({ zIndex: 99 });
                // yMove.animate({
                //     top: yNextPos(i)+"px"
                // }, speed, easing);
                // y2Move.animate({
                //     top: y2NextPos(i)+"px"
                // }, speed, easing);
                
                // MO 231109 - fading headings
                $("p.headings").fadeOut("slow");
                
                var h = $("p.headings:eq("+i+")").text();
                $("p.headings:contains('details')").css({"display" : "none"});
                $("p.headings:contains("+h+")").fadeIn("slow");
                
                // EOF
                
                xMove.animate({
                    left: xNextPos(i)+"px"
                }, speed, easing, function(){ 
                    sliding = false;
                    //yMove.css({ zIndex: 0 });
                });
            }
        }
        // btn clicks
        $("nav").find("a").each(function(i){
            $(this).click(function(e){
                e.preventDefault();
                slide(i);
            });
        });
        $("h1").find("a").each(function(i){
            $(this).click(function(e){
                e.preventDefault();
                slide(0);
            });
        });
        $("#headingsAlt").find("p").each(function(i){
            $(this).click(function(e){
                e.preventDefault();
                slide(i);
            });
        });
    }
}


function projects() {
    
    function closeLB() {
        $("#lb-mask").fadeOut();
        $("#lb").fadeOut();
    }
    
    if($("#lb-mask") && $("#lb") && $("#jobs") && $("#job-title")) {
		$('div.media').each(function() {
			var container = $(this);
			var img = $(this).find('img');
	        var swapping = false;

			container.find('li a').click(function(e) {
				e.preventDefault();
				link = $(this);
				
				if (!swapping) {
					swapping = true;
					var currentLi = container.find('li.current:first');
					var currentLiA = currentLi.find('a');
					
					function loadNewImage(href) {
					    Preloader.add(href);
						Preloader.onFinish(function() {
							img.attr('src', href);
							img.fadeIn(300, function() { swapping = false });
						});
						Preloader.load();
					}
					
					function loadNewVideo(href) {
					    if(isIE) {
					        $(href).show();
					        swapping = false;
					    } else {
					        $(href).fadeIn(300, function() { swapping = false });
				        }
					}
					
					if(currentLiA.hasClass("video")) {
					    var href = link.attr('href');
    					if(isIE) {
    					    $(currentLiA.attr("href")).hide();
    					    if(link.hasClass("video")) {
                        	    loadNewVideo(href);
                        	} else {
                        	    loadNewImage(href);
                            }
    					} else {
                            $(currentLiA.attr("href")).fadeOut(300, function() {
                            	if(link.hasClass("video")) {
                            	    loadNewVideo(href);
                            	} else {
                            	    loadNewImage(href);
                                }
                            });
    					}
					} else {
					    img.fadeOut(300, function() {
    						var href = link.attr('href');
    						if(link.hasClass("video")) {
    						    loadNewVideo(href);
    						} else {
    						    loadNewImage(href);
    						    $(this).parent().attr("href", link.attr("rel"));
						    }
    					});
					}
					currentLi.removeClass('current');
					link.parent().addClass('current');
				}
			});
		});
        
        $("#lb-mask").each(function(i){
            $(this).click(function(e){
                e.preventDefault();
				closeLB();
            });
        });
				
        //         $("#jobs").find("a").each(function(i){
        //             $(this).hover(function(){
        //                 var jobTitle = $(this).attr("title");
        //            $("#job-title").html(" "+jobTitle);
        //            $('#h3_project_title').html(" "+jobTitle);
        //          }, function() {
        //            $("#job-title").html("");
        //          });
        //             $(this).click(function(e){
        //                 e.preventDefault();
        //                 //
        // $('section').hide();
        // $($(this).attr('href')).css('display', 'block');
        // //
        // $('#h3_project_title').html($(this).find("img").attr("alt"));
        // //
        //                 $("#lb-mask").fadeIn();
        //                 $("#lb").fadeIn();
        //                 //
        // $('.tabs li').removeClass('current');
        // $('.tabs a[href=' + $(this).attr('href') + ']').parent().addClass('current');
        //             });
        //         });
      
		$('.tabs a').click(function(e) {
			e.preventDefault();
			
			$('.tabs li').removeClass('current');
			var link = $(this);
			var section = $($(this).attr('href'));
			var header = $('#h3_project_title');
			
			link.parent().addClass('current');
			
			header.fadeOut('medium');
			$('section:visible').fadeOut('medium', function() {
				header.html(link.html());
				header.fadeIn('medium');
				section.fadeIn('medium');
			});
		}).hover(function() {
			$('footer h4').html($(this).html());
		}, function() {
			$('footer h4').html('Projects');
		});
    }
    
    $('a#lb-close').click(function(e) {
		e.preventDefault();
		closeLB();
	});
	
	$(document).keyup(function(e) {
    	if ($('#lb-mask:visible') && e.keyCode == 27) {
    		closeLB();
    	}
    });

}

// 
// function news() {
//     if($("news")) {
//         var news = $("#news");
//         var img = news.find("img:first");
//         var swapping = false;
//         //
//         news.find(".paginator a").click(function(e){
//             e.preventDefault();
//             var clicked = $(this);
//             if (!swapping) {
//                 swapping = true;
//                 news.find("div[id^=stories]:visible").fadeOut(300, function(){
//                     news.find("li.current").removeClass("current");
//                     clicked.parent().addClass("current");
//                     $(clicked.attr("href")).fadeIn(300, function() { swapping = false });
//                 });
//             }
//         });
//         news.find("h4").click(function(e){
//             e.preventDefault();
//             var src = $(this).attr("rel");
//             if (src != "" && src != undefined && !swapping) {
//                 swapping = true;
//                 src = "images/news/" + src + ".jpg";
//                 img.fadeOut(300, function(){
//                     Preloader.add(src);
//            Preloader.onFinish(function() {
//              img.attr('src', src);
//              img.fadeIn(300, function() { swapping = false });
//            });
//            Preloader.load();
//                 });
//             }
//         });
//     }
// }

/* news */

jQuery.ajaxSetup({  
    'beforeSend': function (xhr) {xhr.setRequestHeader("Accept", "text/javascript")}  
});

$(function(){
  $('#jScroll').jScrollPane();
  $('#jScroll2').jScrollPane();
  
  reinitialiseScrollPane = function()
	{
		$('#jScroll').jScrollPane();
	}
  
  $(".post a").bind('click', function(){
    var id = $(this).attr("id");
    $("#jScroll").load("home/post/" + id, "", reinitialiseScrollPane);
    return false;
  });
  
  $('.jScroll_members').jScrollPane();
  
  reinitialiseScrollPane2 = function()
	{
		$('.jScroll_members').jScrollPane();
	}
	
	$("#people-selector li a").bind('click', function(){
    reinitialiseScrollPane2;
    return false;
  });
  
  var projects = 0;
  $("#more_projects").bind('click', function(){
    projects += 4;
    $.post("home/projects", {num : projects}, null, "script");
    $("#less_projects").fadeIn();
    return false;
  });
  
  $("#less_projects").bind('click', function(){
    $("#more_projects").fadeIn();
    projects -= 4;
    $.post("home/projects", {num : projects}, null, "script");
    return false;
  });
  
  $("#jobs li a").live('mouseover', function(){
    var t = $(this).attr("title");
    $("#job-title").text(t);
    Cufon.replace("#job-title");
  });
  
  $("#jobs li a").live('mouseout', function(){
    $("#job-title").text("");
  });
  
$("#jobs li a").live('click', function(e) {
    
    e.preventDefault();
    //
    $('section').hide();
    $($(this).attr('href')).css('display', 'block');
    //
    $('#h3_project_title').text($(this).attr("title"));
    //
    $("#lb-mask").fadeIn();
    $("#lb").fadeIn();
    //
    $('.tabs li').removeClass('current');
    $('.tabs a[href=' + $(this).attr('href') + ']').parent().addClass('current');
    $(".zoom").fancybox();
});
  
});

