var firstSkipped = false;
var footerOpened = false;
var footerOpenedId = '';
var dontHideBg = false;

var urls = {};

if (window.location.hash.length > 0) {
	$('#page-content, #background').hide();
	dontHideBg = true;
}

var browser = '';
if ($.browser.msie) {
	browser = 'msie';
}
else if ($.browser.safari) {
	browser = 'webkit';
}
else if ($.browser.mozilla) {
	browser = 'mozilla';
}

$('html').addClass(browser);


Cufon.DOM.ready(function() {

	Cufon.replace('#latest h1, #title h1, .list-page h1, .list-page h1 span, h1, h1 a, h1 span, #work-back', { fontFamily: 'Futura ExtraBold', letterSpacing: '0px'});
	Cufon.replace('#latest h2, #latest h3, #more-news h2, #more-news h3, #header ul li a, .page-list navigation li a, #language-selector li a, #reeel strong, #reeel li a, #contact strong', { fontFamily: 'Futura Bold', hover: true });
	Cufon.replace('#footerbar div.button div.title span, .overlay-buttons, #geo-redirect ul li', { fontFamily: 'Futura Bold', hover: true });
	Cufon.replace('#work h2, #work h2 span, #contact h3, #contact p small, #legal .notice, .list-page .directors .reelformats a, #play-all, #playlistTitle, #geo-redirect p, #controls', { fontFamily: 'Futura Book', letterSpacing: '1px' });

	Cufon.replace('#live-action li, #animation li, #special-projects li, #stink-network .panel ul li, #contact .panel ul li span, #work .info p, #default-category li ', { fontFamily: 'Futura Book-Bold', hover: true, hoverables: { a: true, span: true } });

	Cufon.replace('.list-page #reel li', { fontFamily: 'Futura Book-Bold', hover: true, hoverables: { a: true, span: true }, letterSpacing: '0.25px' });
//	Cufon.replace('.list-page #reel li', { fontFamily: 'Futura Light-Bold', hover: true, hoverables: { a: true, span: true } });
	Cufon.replace('#search h3', { fontFamily: 'Futura Light' });
	
	Cufon.replace('.ac_results ul li, #search .directors h4', { fontFamily: 'Futura Light-Book', hover: true, hoverables: { a: true } });
	Cufon.replace('#search .search-term', { fontFamily: 'Futura Italic' });
	Cufon.replace('.list-page .navigation li', { fontFamily: 'Futura Bold', hover: true, hoverables: { a: true, span: true } });

});


$(document).ready(function() {
		
	$('#footerbar').show();
	
	$('#headerbar form').submit(function(){
		submitSearch(this);
		return false;
	})
	
	// Add JS detection
	$('html').addClass('js-on');

    $('#search-suggest').autocomplete(globals.urlBasePath + '/search-suggest', {
        
        width: 163,
        selectFirst: false,
        matchSubset: false,
        highlight: function (value, term) {
        	return value;
        },
        parse: function (data) {
            var arr = [];
            for (var i in data.results.film) {
                var cur = data.results.film[i];
                arr.push({ data: cur, value: cur.id });
            }
            return arr;
        },
        formatItem: function (data, i, max, val, term) {            
            var text = '<a href="' + globals.urlBasePath + '/work/' + data.slug + '/" class="xhr"><strong>';
            if (data.client) {
            	text += data.client + ' - ';
            }
            text += data.title + '</strong>' + data.director + '</a>';
            return text;
        }
        
    }).result(function (event, data, formatted) {
    	window.location.hash = '#/work/' + data.slug + '/';
    }).showPanel(function () {
    	$('.ac_results #jscroll').jScrollPane({showArrows:true, scrollbarWidth: 20, scrollbarMargin: 0});
    	Cufon.refresh();
    }).defaultValue({ value: searchTerm });
    
    
/*
	The following code has been uncommented as it downloads every background image for the site.
	This was resulting in 16MB of images being downloaded on the first load. While it doesn't 
	block anything, it seems unnecessary.
	
    $.bgchanger({
    	url: globals.urlBasePath + '/index/backgrounds?format=json',
    	imageUrlBase: globals.urlImagesPath
    });
*/
    

    var morenewsList = $('#more-news ul li');
    for (var i = 0; i < morenewsList.length;) {
    	if (i+1 >= morenewsList.length) break;
    	
    	var h1 = $(morenewsList[ i ]).height();
    	var h2 = $(morenewsList[ i + 1 ]).height();
    	
    	$(morenewsList[ i ]).height(Math.max(h1, h2));
    	$(morenewsList[ i + 1 ]).height(Math.max(h1, h2));
    	i = i + 2;
    }
    
	
    $(document.body).click(function (e) {
    	var target = $(e.target);
    	if (target.is('#footerbar') || !footerOpened) return;
    	
    	if (target.parents('#footerbar').size() == 0) {
			$('#' + footerOpenedId + ' .title').click();
		}
    });
	
	//$('#footerbar .title').hover(Cufon.refresh, Cufon.refresh);
    $('a.xhr, .xhr a, #header ul a').live('click', function () {
        if ($(this).hasClass('noxhr')) return true;
        
        var href = $(this).attr('href').replace(globals.urlBasePath, '');
        window.location.hash = href;
        return false;
    });
    
    if (!firstPageLoad) {
		var timer = setTimeout(function () {
			if (footerOpened && footerOpenedId == 'stink-network') {
				$('#stink-network .title').click();
			}
			clearTimeout(timer);
		}, 2000);
	}


    $.history(function() {
        refresh(true);
    });
    if (window.location.hash) {
	    changeContent();
	}
	else {
	    refresh(false);
	    showContent();
    }
    
	if (!firstPageLoad) {
		$('#stink-network .title').click();
	}


});

function footerOpen(_this) {
    var id = $(_this).parent().attr('id');
    Cufon.refresh('#footerbar div.button div.title span');
	
	if (footerOpenedId != '' && id != footerOpenedId) {
		$('#' + footerOpenedId + ' .title').click();
	}
	
	
    $('#footerbar .panel, #language-selector').fadeOut(100);
    $(_this).parent().find('.panel').fadeIn(100);
    var h = $('#' + id + ' .panel').height();
    var options = {
        height: '+=' + h
    };
    $('#footerbar').animate(options, 200, function () { 
        footerOpened = true;
        footerOpenedId = id;
		$('#footerbar .selected').removeClass('selected').removeClass('close');
        $(_this).parent().addClass('selected').addClass('close');
        Cufon.refresh('#footerbar div.button div.title span');
        
    });
}

function footerClose(_this) {
    if (!footerOpened) return;
    var id = $(_this).parent().attr('id');
    var h = ($(window).scrollTop()+$(window).height()-24);
    Cufon.refresh('#footerbar div.button div.title span');
    
    var options = {
        height: 24
    };
    $('#language-selector').fadeIn(100);
	$('#footerbar .selected').removeClass('selected').removeClass('close');
    $('#' + footerOpenedId + ' .panel').fadeOut(100);
    $('#footerbar').animate(options, 200, function () {

        footerOpened = false;
        footerOpenedId = '';
        Cufon.refresh('#footerbar div.button div.title span');
    });
}

function refresh(flag) {
	flag = flag || false;
	if (flag) {
	    changeContent();
    }
    updateLetterSpacing();
    autoHeightList();
    updateVideoPlayer();
    updateAccordion();
    
}

function changeContent (href) {
    var href = href || window.location.hash || window.location.href.replace(globals.urlBasePath, '');
    if (href.substr(0, 1) == '#') href = href.substr(1);
    
    if (href.length == 0 && !firstSkipped) return false;
	urls[ href ] = urls[ href ] + 1 || 1;
	doXhr(href);
}

function doXhr(href) {
	$.get(globals.urlBasePath + href, {
        format: 'modal'
    }, function (data) {
    	try {
	        var pageTracker = _gat._getTracker(gaCode);
	        pageTracker._trackPageview(href);
        } catch(err) {}


    	$('#page-content, #background').hide();
    	
        $('#page-content').html(data);

        $('#header ul li.selected').removeClass('selected');
        $(data).filter('script').each(function () {
            $.globalEval($(this).text());
        });
        updateLetterSpacing();
        stopTimer(); // videoplayer
        
        showContent(function () {
        	
        	setPlaylistTitle();
	        autoHeightList();
	
	        updateVideoPlayer();
	        updateAccordion();
	        firstSkipped = true;
            Cufon.refresh();
        });
    	
    });
}

function updateLetterSpacing() {
	return; // disabled
	var nodes = {
		'#latest h1': 'latest',
		'#header ul li a': 'navigation',
		'.list-page h1': '',
		'#live-action ul li a': '',
		'#animation ul li a': '',
		'#special-projects ul li a': ''
	};
	var nodeArr = [];
	for (var n in nodes) {
		nodeArr.push(n);
	}
	var rules = {
		'(a)(t)': '<span class="lspacing">$1</span>$2',
		'(v)(a)': '<span class="lspacing">$1</span>$2',
		'(a)(v)': '<span class="lspacing">$1</span>$2'
	};
	$(nodeArr.join(', ')).each(function () {
		var html = $(this).html();
		var fontFamily = $(this).css('font-family');
		var fontSize = $(this).css('font-size');
		for (var r in rules) {
			var reg = new RegExp(r, 'gi');
			html = html.replace(reg, function () {
				var ret = '<span class="lspacing"';
				if ($.browser.msie) {
				 ret += ' style="font-size: ' + fontSize + ';font-family: ' + fontFamily + ';"';
				}
				ret += '>' + arguments[1] + '</span>' + arguments[2];
				return ret;
			});
			$(this).html(html);
		}
	});
}

function autoHeightList() {
    var maxHeight = 0;
    $('#reel li')
        .each(function () { maxHeight = Math.max($(this).height(), maxHeight); })
        .each(function () { $(this).height(maxHeight); });
}

function updateVideoPlayer() {
    /*$('#video').oiplayer({
        server: globals.urlBasePath,
        flash: '/assets/swfs/StinkDigitalPlayerV4.swf',
        controls: 'top'
    });*/
    initVideoPlayer();
}

function updateAccordion() {
    $('.accordion').accordion({ collapsible: true, active: false });
}

function showWorkInfo(){
	$('#work div.info').toggleClass('hidden')
	//$('#work div.info').fadeIn('fast');
}

function hideBg(func) {
    return $('#background').fadeOut(100, func);
}

function showContent(onLoad) {
    var tmp = $('<img />');
    var changed = false;
    var bg = window.backgroundData;
    
    if ($.browser.msie) {
		$('#background').attr('src', $(tmp).attr('src'));
    	$('#background, #page-content').show();
    	if (onLoad) onLoad();
    }
    else {
    	$(tmp).bind('load', function () {
			$('#background').attr('src', $(tmp).attr('src'));
			$('#background, #page-content').show();
			if (onLoad) onLoad();
			$(tmp).unbind('load');
    	});
    	
    	$(tmp).attr('src', bg.bgimage).css('backgroundColor',  bg.bgcolor);
    }
    /*
    if (bg.bgimage) {
        changed = $('#background').attr('src') != $(tmp).attr('src');
    }
	*/
	
    var FullscreenrOptions = {  width: bg.width, height: bg.height, bgID: '#background' };
	jQuery.fn.fullscreenr(FullscreenrOptions);
    
    if (bg.bgcolor) {
        $('body').css('backgroundColor', bg.bgcolor);
    }
}

function submitSearch(form) {
    window.location.hash = '/search/' + form.term.value;
    return false;
}



$(window).bind('ie6update', function() {
	$('#header ul').remove();
	$('#footerbar').remove();
	$('#background').remove();
	$('#body').html('<div id="ie6update"><p>Internet Explorer is missing updated required to view this site.</p><p>Click <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx" class="noxhr">here</a> to update</p></div>');
});


//iSCroll for iPad scrolling/zooming with fixed header footer
function isiPad(){
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	var thisUrl = globals.urlBasePath;
	var iscrollScriptUrl = 'assets/scripts/plugins/iscroll-min.js';

	if (isiPad){

		var iscrollScript = document.createElement( 'script' );
		iscrollScript.type = 'text/javascript';
		iscrollScript.src = thisUrl+iscrollScriptUrl;
		$(iscrollScript).appendTo('head');
		console.log(iscrollScript)

		$('<link href="' + globals.urlBasePath + 'assets/styles/iscroll.css" media="screen" rel="stylesheet" type="text/css" >').appendTo('head');
		

		var myScroll;
		function loaded() {
			myScroll = new iScroll('mainContainer', { zoom: true });
		}
		
		document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
		document.addEventListener('DOMContentLoaded', loaded, false);
		
	}// end isiPad
}
isiPad();


