jQuery.fn.fadeToggle = function(speed, easing, callback){
    return this.animate({
        opacity: 'toggle'
    }, speed, easing, callback);
};

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj){
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

var pid = "";
var currentProject = $('.panel:first');
var filter = "";
var show = "featured";
var mode = "";

var speed = 200;
var size = 60;

var isIE = !$.support.opacity;
var isIE6 = isIE && !window.XMLHttpRequest;

$(document).ready(function(){
	$('body').append($('#popupOverlay'));
	$('body').append($('#popup'));
	$('body').append($('#picknmix-container'));
	
    $('#refine').show();
	$('#selection').show();
	$('#project').hide();
    
    $.address.change(function(event){
        if (event.value != '' && event.value != undefined) 
            getAddress(event.value);
    });
    
    var myHeight = 0;
	if( typeof( window.innerHeight ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientHeight ) ) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	
	$('#popupOverlay').css({"opacity": 0.45});
	
	if (isIE6) {
		$(window).bind('resize.cboxie6 scroll.cboxie6', function () {
			$('#popup').css({width: $(window).width(), top:$(window).scrollTop()+ ($(window).height()/2)});
			$('#popupOverlay').css({position:'absolute', width: $(window).width(), height: $(window).height(), top: $(window).scrollTop(), left: $(window).scrollLeft()});
		}).trigger("scroll.cboxie6");
	}
    
    $(".panel").each(function(){
		$('a div.thumb', this).attr('src', $('a div.thumb', this).css("background-image").replace(/"/g,"").replace(/url\(|\)$/ig, ""));
        $('div.hover', this).css({
            background: "transparent url('" + $('a div.thumb', this).attr('src') + "') bottom left"
        }).hide();
        if (!isIE6) {
            $('div.description', this).css({
                background: "transparent url('" + $('a div.thumb', this).attr('src') + "') top left"
            }).hide();
        }
        
        $(this).click(function(){
			if ($(this).hasClass('filtered')) {
				mode = "filtered";
			} else {
				mode = "";
				
				$('#next').show();
				$('#previous').show();
			}
			currentProject = $(this);
			
            pid = $('a', currentProject).attr('id');
            setAddress();
            return false;
        });
        
        $(this).hover(function(){
			$('.hover', this).show();
            $('.description', this).css({
                opacity: 1,
                "filter": "alpha(opacity = 1)"
            });
            $('.description', this).delay(250).fadeIn("slow");
            $(this).css({
                zIndex: '9999'
            });
        }, function(){
            $('.hover', this).hide();
            $('.description', this).stop().hide();
			$('.description', this).dequeue().stop();
            $(this).css({
                zIndex: '0'
            });
        });
    });
    
    $('.closeButton').click(function(event){
		if ($(event.target).hasClass('closeButton')) {
			$('#project').hide();
			$('#popup').hide();
			$('#popupOverlay').fadeOut();
			var y = $(document).scrollTop();
			if (typeof(window.innerHeight) != 'number') {
				document.documentElement.style.overflow = document.body.style.overflow = 'auto';
				$('html').css('border-right','none');			
				$('#plane').css('margin-right','0');
			}
			$(document).scrollTop(y);
			pid = "";
			setAddress();
		}
    });
    
    $('#picknmix_btn').click(function(){
		var y = $(document).scrollTop();
		if (typeof(window.innerHeight) != 'number') {
			document.documentElement.style.overflow = document.body.style.overflow = 'hidden';
			$('html').css('border-right','16px solid #CCC');
			$('#plane').css('margin-right','16px');
		}
		$(document).scrollTop(y)
		$('#popupOverlay').addClass("backtostudio");
        $('#popupOverlay').fadeIn();
        $('#picknmix-container').show();
		
		$('.backtostudio').click(function(event){
			if ($(event.target).hasClass('backtostudio')) {
				$('.backtostudio').click(function(){});
				$('#popupOverlay').removeClass("backtostudio");
				filter = "";
				show = "";
				
				$('#show input:checked').each(function(){
					show += $(this).val() + ",";
				});
				
				show = show.slice(0, show.length - 1);
				
				$('#filter input:checked').each(function(){
					filter += $(this).val() + "|";
				});
				
				if (filter == "") {
					if (show == "all") {
						$('.panel').show();
					}
					else {
						$('.panel:not(.featured)').hide();
						$('.panel.featured').show();
					}
				}
				
				filter = filter.slice(0, filter.length - 1);
				
				setAddress();
				$('#popupOverlay').fadeOut();
				var y = $(document).scrollTop();
				if (typeof(window.innerHeight) != 'number') {
					document.documentElement.style.overflow = document.body.style.overflow = 'auto';
					$('html').css('border-right','none');			
					$('#plane').css('margin-right','0');
				}
				$(document).scrollTop(y)
				$('#picknmix-container').hide();
			}
	    });
    });
	
	$('#filter input').click(function(){
		if($('#filter input:checked').length > 0){
			$('#show input').removeAttr('checked');
			$('#show input#filtered').attr('checked', 'checked');
			$('#show input').trigger('updateState');
		} else {
			$('#show input').removeAttr('checked');
			$('#show input#featured').attr('checked', 'checked');
			$('#show input').trigger('updateState');
		}
	});		
	
	$('#show input:not(#filtered)').click(function(){
		$('#filter input').removeAttr('checked');
		$('#filter input').trigger('updateState');
	});		
    
    $('input').customInput();
	
    $('#next').click(function(){
		updatePanel(1);
        $('#next').hide();
        $('#previous').hide();
    });
    
    $('#previous').click(function(){
        updatePanel(-1);
        $('#next').hide();
        $('#previous').hide();
    });
});

function updatePanel(change){
	
	$('#project').hide();	
	$('#loading').show();
	
    if (change > 0) {
		if(mode == "filtered")
			currentProject = currentProject.nextAll('.filtered:first');
		else
			currentProject = currentProject.nextAll(':visible:first');
  		if ($('a', currentProject).attr('id') == undefined) {
			if (mode == "filtered") 
				currentProject = $('.panel.filtered:visible:first');
			else 
				currentProject = $('.panel:visible:first');
		}
    }
    else if (change < 0) {
		if(mode == "filtered")
			currentProject = currentProject.prevAll('.filtered:first');
		else
			currentProject = currentProject.prevAll(':visible:first');
        if ($('a', currentProject).attr('id') == undefined) {
			if (mode == "filtered") 
				currentProject = $('.panel.filtered:visible:last');
			else 
				currentProject = $('.panel:visible:last');
		}
    }
		
	pid = $('a', currentProject).attr('id');
	setAddress();
}

function updateProject(){
    $.ajax({
        type: "get",
        dataType: "json",
        url: "/portfolio.front.getProjectJSON",
        data: {
            resourceUrl: "/portfolio/" + pid
        },
        success: function(data){		
			var string = ""
			if (data.small_logo) {
				if (data.clienturl) {
					string += '<a href="/clients' + data.clienturl + '.cfm">';
				}
				string += '<img alt="' + data.clientname + ' Logo" src="' + data.small_logo + '" width="111" height="70" />'
				if (data.clienturl) {
					string += '</a>\n';
				}
				$('#details #client').html(string).show();
			} else {
				$('#details #client').html(string).hide();
			}
			
            $('#details #title h2').html(data.title);
			
			$('#details #print a').attr('href', '/portfolio.front.getProjectPDF?resourceUrl=/portfolio/' + pid);
			
			if(data.externalurl != ""){
				$('#details #url a').attr('href', data.externalurl).show();
				var ma = data.externalurl.match(/^(https?:\/\/)(www\.)?([^/]+)?/i);
				if(data.externalurl == ma[1] + ma[2] + ma[3]){
					$('#details #url a').html(ma[2] + ma[3]);
					$('#details #url').show();
				} else {
					$('#details #url a').html('View Live Project');
					$('#details #url').show();	
				}
			} else	{
				$('#details #url').hide();
			}
			
			$('#details div#body').html(data.keyfeatures + data.body);
            var slides = '<div id="slides">\n';
            $.each(data.slides, function(i, objValue){
				totalLoading++;
                slides += '<img class="loadable-image" src="' + objValue + '"/>\n';
            });
            slides += '</div>';
            $('#slideshow').html(slides);
			updateSlideShow();
				
			$('.loadable-image').each(function(){
				if($(this).complete){
					totalLoading--;
				}
			});
			
			if (totalLoading == 0) {
				displayProject();
			} else {
				$('.loadable-image').load(checkDisplay);
			}
        },
        timeout: function(data){
            alert("timeout");
        }
    });
}

var totalLoading = 0;
function checkDisplay(){
	totalLoading--;
	if(totalLoading == 0){
		displayProject();
	}
}
function displayProject(){
	if (currentProject.hasClass('filtered')) {
		$('#panel').addClass('filtered');		
	} else {
		$('#panel').removeClass('filtered');
	}
	
	if(mode == "filtered"){
			$('#next').addClass('orangeButton');	
			$('#previous').addClass('orangeButton');
	} else {
		if ($('a', currentProject.nextAll(':visible:first')).attr('id') == undefined) {
			if ($('.panel:visible:first').hasClass('filtered')) {
				$('#next').addClass('orangeButton');
			} else {
				$('#next').removeClass('orangeButton');
			}
		} else {
			if (currentProject.nextAll(':visible:first').hasClass('filtered')) {
				$('#next').addClass('orangeButton');
			} else {
				$('#next').removeClass('orangeButton');
			}
		}
		
		if ($('a', currentProject.prevAll(':visible:first')).attr('id') == undefined) {
			if($('.panel:visible:last').hasClass('filtered')){
				$('#previous').addClass('orangeButton');	
			} else {
				$('#previous').removeClass('orangeButton');
			}
		} else {
			if(currentProject.prevAll(':visible:first').hasClass('filtered')){
				$('#previous').addClass('orangeButton');
			} else {
				$('#previous').removeClass('orangeButton');
			}	
		}
	}
	
	$('#loading').hide();
	if ($('#popup').is(':visible') && $('#project').is(':hidden')) {
		$('#project').show();
		$('#details div#body').scrollTop(0);
	}
	
	if(mode == "filtered" && $('.panel.filtered').size() > 1) {
		$('#next').show();
		$('#previous').show();
	} else if(mode == "filtered") {
		$('#next').hide();
		$('#previous').hide();
	} else {
		$('#next').show();
		$('#previous').show();
	}
}

var timer;

function slideTimer(){
    timer = setInterval("nextSlide()",4000);
}

function nextSlide(){
    var current = $('#slides').children('img:visible');
    current.fadeOut();
    var next;
    if (current.next().is('img')) {
        next = current.next().fadeIn();
    }
    else {
        next = current.parent().children(':first').fadeIn();
    }
    
    $('#thumbnails').children('li').children('img').parent().removeClass('current');
    $('#thumbnails').children('li').children('img[sid=' + next.attr('sid') + ']').parent().addClass('current');
}

function updateSlideShow(){

    if (timer) {
        clearInterval(timer);
    }
    
    $('#slides').after('<ul id="thumbnails" style="list-style-type:none;" />');
    
    $('#slides').children('img').each(function(i){
        $('#thumbnails').append('<li class="ui-corner-all"><img sid="' + i + '" class="thumbnail" src="' + $(this).attr('src') + '" /></li>');
        $(this).addClass('off stage').attr('sid', i);
    });
    
    slideTimer();
    
    $('#thumbnails').children('li').children('img').click(function(){
		 clearInterval(timer);
        if (!$(this).parent().hasClass('current')) {           
            $('#slides').children('img:visible').fadeOut();
            $('#slides').children('img[sid=' + $(this).attr('sid') + ']').fadeIn();
            
            $(this).parent().parent().children('.current').removeClass('current');
            $(this).parent().addClass('current');
        }
        
        return false;
    });
    
    $('#slides').children('img:first').removeClass('off');
    $('#thumbnails').children('li:first').addClass('current');
}

function setAddress(){
    var queryString = "";
    
    if (pid != "") {
        queryString += pid + "&";
    }
    
    if (filter != "") {
        queryString += "filter=" + filter + "&";
    }
    
    if (show != "") {
        queryString += "show=" + show + "&";
    }
    
    queryString = queryString.slice(0, queryString.length - 1);
    
    $.address.value(queryString);
}

function getAddress(address){

    if (address.indexOf("&") != -1) {
        var splitAddress = address.split("&");
        for (var i = 0; i < splitAddress.length; i++) {
            if (splitAddress[i].indexOf("show=") != -1) {
                show = splitAddress[i].replace("show=", "");
            }
            else 
                if (splitAddress[i].indexOf("filter=") != -1) {
                    filter = splitAddress[i].replace("filter=", "");
                }
                else {
                    pid = splitAddress[i];
                    currentProject = $('#'+pid).parent();
                }
        }
    }
    else {
        if (address.indexOf("show") != -1) {
            show = address.replace("show=", "");
        }
        else 
            if (address.indexOf("filter") != -1) {
                filter = address.replace("filter=", "");
            }
            else {
                pid = address;
                currentProject = $('#'+pid).parent();
            }
    }
	
	if (show != "") {
		$('#show input').removeAttr('checked');
		$('#show input#' + show).attr('checked', 'checked');
		$('#show input').trigger('updateState');
	}
	
    if (pid != "") {
		var y = $(document).scrollTop();
		if (typeof(window.innerHeight) != 'number') {
			document.documentElement.style.overflow = document.body.style.overflow = 'hidden';
			$('html').css('border-right','16px solid #CCC');
			$('#plane').css('margin-right','16px');
		}
		$(document).scrollTop(y)
        $('#popupOverlay').fadeIn();
		$('#loading').show();
        $('#popup').fadeIn();
        updateProject();
    }
    
    if (filter != "") {
	
		var terms = filter.split("|");
		var termList = "";
		
		$('#filter input').removeAttr('checked');
		for (var i = 0; i < terms.length; i++) {
			$('#filter input').each(function(){
				if ($(this).val() == terms[i]) 
					$(this).attr('checked', 'checked');
				$(this).trigger('updateState');
			});
			
			if (i == 0) 
				termList += '<span class="orange">' + $('label[for=' + terms[i] + ']').html() + '</span>';
			else 
				if (i != terms.length - 1) {
					termList += ', <span class="orange">' + $('label[for=' + terms[i] + ']').html() + '</span>';
				}
				else {
					termList += ' and <span class="orange">' + $('label[for=' + terms[i] + ']').html() + '</span>';
				}
		}
		
		if ($('#terms').html() != termList) {
			$('#terms').html(termList);
			
			$.getJSON("/portfolio.search.doSearchJSON?term=" + filter.replace(new RegExp(/\//g), ""), function(data){
			
				if (show == "all") {
					$('.panel').show();
				}
				else 
					if (show == "filtered") {
						$('.panel.featured').show();
						$('.panel:not(.featured)').hide();
					}
					else {
						$('.panel:not(.featured)').hide();
						$('.panel.featured').show();
					}
				
				// colour only the search results
				$('.panel').removeClass('filtered');
				$.each(data, function(i, item){
					$('.panel#' + item).addClass('filtered');
				});
				
				// grey out results
				$('.panel:not(.filtered)').each(function(){
					$('a div.thumb', this).css({
						backgroundPosition: "bottom right"
					});
				});
				
				$('.panel.filtered').each(function(){
					$('a div.thumb', this).css({
						backgroundPosition: "top right"
					});
				}).show();
				
			});
		}
	}
	else {
		
		$('.panel').removeClass('filtered');
		
		if (show != "") {
			if (show == "all") {
				$('.panel').each(function(){
					$('a div.thumb', this).css({
						backgroundPosition: "top right"
					});
					$(this).show();
				});
				$('.panel').addClass('filtered');
			}
			else {
				
				$('.panel:not(.featured)').hide();
				$('.panel.featured').show();
				
				$('.panel.featured').each(function(){
					$('a div.thumb', this).css({
						backgroundPosition: "top right"
					});
				});
				$('.panel.featured').addClass('filtered');
			}
			
			$('#terms').html('<span class="orange">' + $('label[for=' + show + ']').html() + '</span>');
		}
	}
	
}