var url_paths = new Array();
var resize_timer = null;
var windowWidth;
var windowHeight;
var first;
var second;
var last;
var second_last;
var current_slide = 0;
var shellUp = false;
var animSequence = new Array();
var videoPlayer;
var currentFile;
var fileClone;
var facebookBlocked = false;

var img = new Image();
img.onerror = function () {
	facebookBlocked = true;
}
img.src = "http://facebook.com/favicon.ico";

function init(){

	onWinResize();

	setupResizeEvent();
	setupCountdown();
	url_paths = window.location.pathname.split( '/' ).clean("");
	last = url_paths[url_paths.length-1];
	second_last = url_paths[url_paths.length-2];
	first = url_paths[0];
	second = url_paths[1];
	if (last == undefined){ // prob on home
		last = "";
	}
	
	if (last == "") setupHomepage();
	if (first == "supporters") setupSupporters();
	if (first == "days-made-better") setupSearch();
	if (first == "get-involved") setupGetinvolved();
	//if (first == "upload") setupUpload();
}

function setupUpload(){
	currentFile = 0;
	fileClone = $("#file_upload").clone();
	
	$("#file_upload input[name=userfile]").attr("name", "userfile"+currentFile);
	$("#file_upload textarea[name=photo_caption]").attr("name", "photo_caption"+currentFile);
	$("#file_upload").attr("id", "file_upload"+currentFile);
	
	
	$("#add_file").click(function(e){
		currentFile++;
		var newClone = fileClone.clone();
		newClone.attr("id", "file_upload"+currentFile);
		newClone.find("input[name=userfile]").attr("name", "userfile"+currentFile);
		newClone.find("textarea[name=photo_caption]").attr("name", "photo_caption"+currentFile);
		$("#upload_form input[name=upload_cnt]").attr("value", currentFile+1);
		$(this).before(newClone);
		//$(this).before("<br>");
		return false;
	});
}

function setupGetinvolved(){
	var images = $("#get_involved div.intro_pics div.img");
	var rand = Math.floor(Math.random()*images.length);
	var elem = images.eq(rand);
	elem.css('zIndex', '1000');
}

function setupResizeEvent(){
	$(window).bind("resize", function(){
		onWinResize();
	});
}

function onWinResize(){
	windowWidth = $(window).width();
	windowHeight = $(window).height();
	try{
		if($.browser.msie && $.browser.version=="6.0"){
			
		} else {
			resizeHomepage();
		}
	} catch (e){}
	if (shellUp == true){
		var shell = $("#player_shell");
		shell.width(windowWidth);
		shell.height(windowHeight);
		shell.css({'paddingTop': windowHeight/2 - 456/2, opacity: 1.0});
	}
}

function setupCountdown(){
	$("#countdown").hover(function() {
	    animateCountdown('mouseover');
	}, function(){
		animateCountdown('mouseout');
	});
	//All options
    $("#time").countdown({
        date: "october 2, 2012 10:00",
        htmlTemplate: "%{d} <span>Days</span> %{h} <span>Hrs</span> %{m} <span>Mins</span>",
        onChange: function( event, timer ){
 
            /*
            Tips:
 
            event.target is DOM Element
            this is DOM element
            $(this) is jQuery Element
            timer is interval for countdown
 
            If a countdown should end early you could do:
 
            clearInterval( timer );
            $(this).trigger('complete');
            */
 
        },
        onComplete: function( event ){
            //$(this).html("Completed");
        },
        minus: false, //defaults to false anyway
        leadingZero: true
    });
}

function resizeHomepage(){
	var slideshow_view = $('#main_slideshow');
	var slideshow_yPos = (windowHeight/2) - 315;
	slideshow_view.css({ 'height' : '470px', 'top' : slideshow_yPos + 'px' })
}

function setupHomepage(){

	// setup slide next/prev buttons
	if($.browser.msie && $.browser.version=="6.0"){
		
	} else {
		$('#main_slideshow').append(
			'<div id="main_slideshow_prev"><a href="#">Previous</a></div><div id="main_slideshow_next" class="next"><a href="#">Next</a></div>'
		);

		// video link buttons
		$('a.videobtn').css({ 'filter' : 'none !important', 'opacity' : '0.9' });
	
		$('a.videobtn').hover(
			function(){
				$(this).css({ 'cursor' : 'pointer' });
				$(this).css({ 'filter' : 'none !important' }).animate({ 'opacity' : '1.0'}, 300);
		
			}, function(){
				$(this).removeClass('active');
				$(this).css({ 'filter' : 'none !important' }).animate({ 'opacity' : '0.9'}, 300);
			}
		);
	
		// setup slideshow
		resizeHomepage();

		// setup slideshow navigation
		var slideshow_links = $("#main_slideshow_prev a, #main_slideshow_next a");
		var slideshow_nav = $("#main_slideshow_prev, #main_slideshow_next");

		slideshow_nav.css({ 'cursor' : 'pointer', 'filter' : 'none !important' }).delay(1000).animate({ 'opacity' : 0.5 }, 800);
		slideshow_links.text("");
		slideshow_nav.bind({
			mouseenter: function() {
				$(this).addClass('slidenav_hover');
				if($(this).hasClass('next')) {
					$(this).animate({
						'filter' : 'none !important',
						'opacity'	: 1.0,
						'right'		: '0px'
					}, 300)
				} else {
					$(this).animate({
						'filter' : 'none !important',
						'opacity'	: 1.0,
						'left'		: '0px'
					}, 300)
				}
			},
			mouseleave: function() {
				$(this).removeClass('slidenav_hover');
				if($(this).hasClass('next')) {
					$(this).animate({
						'opacity'	: 0.5,
						'right'		: '-10px'
					}, 300)
				} else {
					$(this).animate({
						'opacity'	: 0.5,
						'left'		: '-10px'
					}, 300)
				}
			},
			click: function() {
				moveSlide($(this).attr('id'));
			}
		});
	
		// setup slideshow panels
		var slides = $("#main_slideshow div.slide");
		slides.css({'border-top':'none'}).hide();
		slides.each(function(index) {
			$('#slide_pagination').append('<span onclick="moveSlide(' + (index) + ');">' + (index+1) + '</span>');
		});
		moveSlide(0);
	}
	$("#main_slideshow #slide2 a.video, #main_slideshow #slide3 a.video").click(function(e){
		var deviceAgent = navigator.userAgent.toLowerCase();
		var appleDevice = deviceAgent.match(/(iphone|ipod|ipad)/);
		if (!appleDevice) {
			launchVideo($(this).attr('href'));
			return false;
		}		
	});
}

function moveSlide(nav_id){
	var slides = $("#main_slideshow div.slide");
	var slidenav = $("#slide_pagination span");
	if (nav_id == "main_slideshow_prev"){
		current_slide--;
	} else if (nav_id == "main_slideshow_next"){
		current_slide++;
	}
	if (current_slide < 0) current_slide = 0;
	if (current_slide > slides.length-1) current_slide = slides.length-1;
	var all_except = $("#main_slideshow div.slide:not(:eq("+current_slide+"))");
	var selected = $("#main_slideshow div.slide:eq("+current_slide+")");
	all_except.stop(true,false).fadeOut(300);
	if(current_slide == 0) $('#slide1 .slide_visual img').hide();
	selected.stop(true,false).delay(800).fadeIn(500, function() {
		if(current_slide == 0) animate_slideIntro();
	});
	slidenav.removeClass('curr');
	slidenav.eq(current_slide).addClass('curr');
	$("#main_slideshow_prev, #main_slideshow_next").show();
	if (current_slide == 0) $("#main_slideshow_prev").hide();
	if (current_slide == slides.length-1) $("#main_slideshow_next").hide();
	//all_except.fadeOut('fast');
	//selected.fadeIn('fast');
	//selected.css('paddingTop', (windowHeight/2) - ($(this).height()/2));
}

function animate_slideIntro() {
	var targetObj = $('#slide1 .slide_visual img');
	targetObj.hide();
	targetObj.each(function() {
		animSequence.push($(this));
	});
	doAnimation(animSequence.shift());	
}

function doAnimation(image) {
    image.stop(true,false).fadeIn("normal", function() {
        if(animSequence.length > 0) doAnimation(animSequence.shift());
    });
}



function setupSupporters(){
	$('#celebrity_grid .profile').hover(
		function(){
			$(this).css({ 'cursor' : 'pointer' });
			$(this).addClass('active');
			$(this).find('a').addClass('hover');
		
		}, function(){
			$(this).removeClass('active');
			$(this).find('a').removeClass('hover');
		}
	)
	
	$('#celebrity_grid .profile').click(function(e){
	
		e.preventDefault();
		var itemURL = $(this).find('a').attr('href');
		window.location = itemURL;
	
	});
}

function setupSearch(){

	setInterval('rotateImages()', 4000 );

	$('#search_results li').hover(
		function(){
			$(this).css({ 'cursor' : 'pointer' });
			$(this).find('.teacher').addClass('yellow');
			$(this).find('span:first').stop(true,false).animate({
				'margin-left' : '15px'
			}, 300)
		
		}, function(){
			$(this).find('.teacher').removeClass('yellow');
			$(this).find('span:first').animate({
				'margin-left' : '0'
			}, 300)
		}
	)
	$('#search_results li').click(function(e){
		e.preventDefault();
		var itemURL = $(this).find('a').attr('href');
		window.location = itemURL;
	
	});
	$("#search_reset").click(function(e){
		$(this).siblings('input.serif').attr("value", "").focus();
		return false;
	});
	$("#search_date li").css('cursor', 'pointer');
	$("#search_date li").click(function(e){
		var year = $(this).find('span').text();
		$("#search_date li").removeClass('active');
		$(this).addClass('active');
		$("#search_field input[type=hidden]").attr("value", year);
		return false;
	});
	if (!second) clearOrRestoreForm();
}

function rotateImages() {
    var $active = $('#rotate_images img.active');
    if( $active.length == 0 ) $active = $('#slideshow img:last');
    var $next =  $active.next().length ? $active.next()
        : $('#rotate_images img:first');
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
    });
}


// start it up
$(function(){
	
	init();
    
	$('#content .pagination_btm a').click(function(e){
		e.preventDefault();
		$('html, body').animate({
			scrollTop : '0px'
		}, 500, "easeOutQuad")
	});
	
});

function animateCountdown(str) {
	var obj = $('#countdown');
	if(str == "mouseover") {
		obj.css({ 'cursor' : 'default' });
		obj.children('div:first-child').animate({
			'margin-top' : '-55px'
		}, 300)
	} else {
		obj.children('div:first-child').animate({
			'margin-top' : '0px'
		}, 300)
	}
}

function clearOrRestoreForm(){
	var inp = document.getElementsByTagName('input');
	for(var i = 0; i < inp.length; i++) {
		if(inp[i].type == 'text') {
			inp[i].setAttribute('rel',inp[i].defaultValue)
			inp[i].onfocus = function() {
				if(this.value == this.getAttribute('rel')) {
					this.value = '';
				} else {
					return false;
				}
			}
			inp[i].onblur = function() {
				if(this.value == '') {
					this.value = this.getAttribute('rel');
				} else {
					return false;
				}
			}
			inp[i].ondblclick = function() {
				this.value = this.getAttribute('rel')
			}
		}
	}
}

function launchVideo(video_path){
	//var video_path = "/assets/media/ADMB_Cause_Video.mp4";
	var player_path = "/assets/swf/player.swf";
	var skin_path = "assets/swf/skins/mySkin.swf";
	var close = $("#player_shell img.close-video");
	var container = $("<div id='admb_video'></div>");
	//var container = $("#zoom_content");
	
	var timestamp = Math.floor(Math.random()*10000);
	var params = {
		quality: "high",
		scale: "noscale",
		// wmode: "window",
		allowscriptaccess: "always",
		allowFullScreen: "true",
		bgcolor: "#000"
	};
	var flashvars = {
		skin: skin_path,
		video: video_path,
		autoplay: 1,
		thumbnail: ""
	};
	var attributes = {
		id: "admb_video",
		name: "admb_video"
	};
	var shell = $("#player_shell");
	shellUp = true;
	shell.fadeIn();
	shell.width(windowWidth);
	shell.height(windowHeight);
	shell.css({'paddingTop': windowHeight/2 - 456/2, opacity: 1.0});
	shell.prepend(container);
	shell.prepend(close);
	
	swfobject.embedSWF(player_path+"?t="+timestamp, "admb_video", "604", "456", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	shell.find("#admb_video").css({'left':windowWidth/2 - 604/2});
	//shell.find("#cover").height(windowHeight - 560);
	shell.find("#cover").height(1);
	close.css({"zIndex": 12000, 'right':windowWidth/2 - 335, 'position':'absolute'});
	
	$("#player_shell img.close-video").live('click', function(e){
		swfobject.removeSWF("admb_video");
		$(this).parent().fadeOut();
		shellUp = false;
		return false;
	});
}






Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {         
      this.splice(i, 1);
      i--;
    }
  }
  return this;
};

