// This is pretty useful. 
(function($){
    $.fn.whenLoaded = function(fn){
        var $elements = this,
            total = this.length;
        $elements.each(function(){
            $(this).load(function(){
                $(this).data('isLoaded',true);
            });
        });
        function check() {
            var loaded = 0;
            $elements.each(function(){
                if($(this).data('isLoaded')) {
                    loaded++;
                }
            });
            if(loaded===total) {
                fn.call($elements);
            } else {
                setTimeout(check,300);
            }
        }
        check();
    }
})(jQuery);
function makeslider(c,nolis) {
	var container = $(c);
    var ul = $(c+' ul');
   	var sla = ul.innerWidth()/(200*nolis);
    var itemsWidth = ul.innerWidth() - container.outerWidth();
   
    $('.slider').slider({
        min: 0,
        max: 600,
        handle: '.handle',
        stop: function (event, ui) {
            //ul.animate({'left' : ui.value * -1}, 500);
        },
        slide: function (event, ui) {
            ul.css('left', ui.value * sla*-1);
            $(".handle").css('left',ui.value);
        }
    });
}
function setupPanelHeights(crackdealer) {
	
	var brooklyn = ($('iframe').height()+$('iframe').offset().top)-($('#sidebar').height()+$('#sidebar').offset().top);
	if ((brooklyn>0)){ 
		$('#sidebar').height($('#sidebar').height()+brooklyn-32); 
		k=false; 
	}
	
	if(($('#mainContent').height()-15)>$('#sidebar').height()){
		$('#sidebar').height($('#mainContent').height()-15);
		//alert("maincontent gt sidebar");
	}
	else if(($('#mainContent').height()-15)<$('#sidebar').height()) {
		$('#mainContent').height($('#sidebar').height()+15);
		//alert("maincontent lt sidebar");
	}
	/*
	if ($('#sidebar').height() > ($('#mainContent').height()-15)) {
		$('#mainContent').height($('#sidebar').height()+15);
	}
	*/
}
var raindrops;
var kpz;
function setupMenu() { 
	kpz=$("#menuContainer").offset().left+"px"; 
	$('#menuContainer ul li').each(function() {
		if($(this).parent().parent().attr("id") == "menuContainer") {
			if ($(this).children("ul").html() == null) {
					$(this).append('<ul style="z-index: 10000"></ul>');
			}
		}
	});
	
	//alert(kpz+" - "+$("#menuContainer").offset().left);
	$("#menuContainer ul li").each(function(){
		$(this).children("ul").css("left",kpz);
	});
	$('#sidebar').height($('#mainContent').height()-15);
}
function setupOverlay(){
	var goldenale=$("#menuContainer ul li:first").offset().left+10+"px";
	$("#interested_sponsors").css("left",goldenale);
}
// Function to cycle through the images. Not the most elegant, a rewrite entirely is in order.
var mv=4; var m=2; var bz;
function t() {    
	if(mv!=0) {
		$('#slider .navigation').find('a[href$="' + m + '"]').click();    
		if(m==mv) m=1;
		else m++;
	} 
}
var b = 200;
function pauseSlider(jazz){
	m = (jazz==4) ? 1 : jazz+1;
	clearInterval(bz);
	$("#pausedSliderOverlay").fadeIn(750).children("#pausebutton").fadeOut(b).fadeIn(b).fadeOut(b).fadeIn(b).fadeOut(b).fadeIn(b);
}
function resumeSlider(){
	t();
	bz=setInterval(function(){t()},5000);
	$("#pausedSliderOverlay").fadeOut(500);
}
function showPanel(url){
	var img = new Image();
	$(img).load(function () {
		// set the image hidden by default    
		$(this).hide();
		// then insert our image
		$("#panelContainer").prepend(this);
		// fade our image in to create a nice effect, callback function removes the previous image so they don't stack
		$(this).fadeIn(2000, function(){
			//If there are more panels, put this back in. It's so they don't stack ontop of each other.
			//$("#panelContainer img:first").remove();
		});  
	}).error(function () {
	      // notify the user that the image could not be loaded
	    }).attr('src', url);		    
}

function showCurNav (){
	var url = new String (window.location);
	var urlparts = url.split('/');
	var host = urlparts[urlparts.length-1];
	var soup=0;
	$("#menuContainer ul li a[href$='"+host+"']:first").each(function(){
		$(this).parent().css({"background-color" : "#52B3D1", "-moz-border-radius-topleft" : "4px", "-moz-border-radius-topright": "4px"})
			.children("ul").css({ "visibility" : "visible", "display" : "block", "z-index" : "9999"});
		soup = 1;
	});
	$("#menuContainer ul li ul li a").each(function(){
		if($(this).parent().parent().css("visibility")!="visible"){
			$(this).parent().parent().css("z-index",(9999+soup));
		}
	});
	$("#menuContainer ul li ul li a[href$='"+host+"']").each(function(){		
		$(this).parent().parent().css("z-index",9998);
		$(this).parent().css({"background-color" : "#505050", "-moz-border-radius-topleft" : "4px", "-moz-border-radius-topright": "4px"})
			.parent().css({ "visibility" : "visible", "display" : "block"})
			.parent().css({"background-color" : "#52B3D1", "-moz-border-radius-topleft" : "4px", "-moz-border-radius-topright": "4px"});
	});
}
function makeReliable (){
	setupPanelHeights();
	setupMenu();
}
function setupTwitter(){
	$("#twitter").getTwitter({
		userName: "sunswift",
		numTweets: 4,
		loaderText: "Loading...",
		slideIn: false,
		showHeading: false,
		headingText: "",
		showProfileLink: false
	});	
}
var videoadded=false;
/********
Videos
*********/
var videos;
function setVideos (from_vimeo) { videos = from_vimeo; }

function showVideos () {
	clearInterval(bz);
    $("#panelContainer").html("<div class='video-loader'><span id='loader-text'><img style='position:relative' src='/themes/Sunswift/images/loader.gif' /></span></div>");
    $(".video-loader").animate( {'opacity':1},200);
	$("#panelContainer").append("<div id='videos'><ul></ul><div class='slider'><div class='handle'></div></div></div>");
    var imgwidth=200;
    // Add the Li's
    var x=1; // For testing purposes.
    while(x<2){
	    for (var i = 0; i < videos.length; i++) {
			addVideoLi(i,videos[i].thumbnail_medium, imgwidth, videos[i].title);
	    }
	    x++;
    }
	//Make the ul big enough
	var w = videos.length*240;
    if (w<780) w = 780;
    $("#videos ul").width(w);
    if (w>780) makeslider('#videos',videos.length);
	else $(".slider").remove();
	//Style overlays
	
	if (navigator.appName=="Opera") {
		$("#videos ul li a img").ready(function() {
			makeOverlays (".vidthumb");
			$(".video-loader").animate( {'opacity':0.01},300,function(){$(".video-loader").remove();});
		});
	}
	else {
		$("#videos ul li a img").whenLoaded(function() {
			makeOverlays (".vidthumb");
			$(".video-loader").animate( {'opacity':0.01},300,function(){$(".video-loader").remove();});
		});			
	}    
}
function playVideo (index) {
	var specialsausage;
	// This is how much the bar must move down
	specialsausage = ((videos[index].height/videos[index].width)*780)-225;
	specialsausagepx = specialsausage + 'px';
	//alert(specialsausagepx);
	// This is the height of the video
	var h = ((videos[index].height/videos[index].width) *780)+'px';	
	
	var bongwater=0; var kebabinstalled=false;
	$(".navigation").hide();
	$(".scroll").animate({ height:h },400);
	$("#videos").animate({ height:h },400,function(){
		$("#videos").css("display","block");
		makeBackButton("videos");
	});
	var adjh= (((videos[index].height/videos[index].width) *780)+downbuffer)+"px";
	$("#mainContent").animate({ marginTop:adjh },300);
	$("#sidebar").animate({ marginTop:adjh },300);
	$("#videos").css({
		"position":"absolute",
		"top" : "0",
		"left" : "0",
		"padding" : "0",
		"margin" : "0",
		"display" : "none",
		"z-index" : "99"
	});
	$("#videos").flash({
		swf:'http://www.vimeo.com/moogaloop.swf?autoplay=1',
		width: 780,
		height: h,
		wmode: "transparent",
		flashvars: {
	        clip_id: videos[index].id,
	        show_portrait: 0,
	        show_byline: 0,
	        show_title: 0,
			js_api: 1, // required in order to use the Javascript API
			width: 780,
			height: 225
		}
	});	
}

function addVideoLi (j, url, width, title) {	
	$("#videos ul").append('<li><div onClick="playVideo(\''+j+'\'); return false;" ><span class="thumb_overlay">'+title+'</span></div><a href="javascript:;" onclick="playVideo(\''+j+'\'); return false;"><img class="vidthumb" border="0" src="'+url+'" /></a></li>');
	$(".vidthumb:last").ready(function() {
		// First we style the overlay div.
		//Add the reflection
		$(".vidthumb:last").reflect().css("position", "relative");		
	});


}

function makeBackButton (b) {
	if (b=="galleries") w = "-144px";
	else if (b=="videos") w = "-130px";
	$("#panelContainer").prepend('<div id="backbutton"><a href="#" onclick="goBack(\''+b+'\'); return false;">Back to '+b+'<img width="20" style="position: relative; padding-left: 4px; top: 4px; border: 0" src="/themes/Sunswift/images/back-button.png"/></a></div>');
	$("#backbutton").bind("mouseenter", function() {
		$("#backbutton").animate({ left: "0px" }, 400);
	});
	$("#backbutton").bind("mouseleave", function() {
		$("#backbutton").animate({ left: w }, 400);
	});
	$("#backbutton").animate({ left: w }, 400); 
}
function goBack(to) {
	videoadded = false;
	if (to=="videos") { 
		$("#videos").fadeOut(400, function(){
			$("#videos").remove();
			$("#mainContent").animate({ marginTop:0 },400);
			$("#sidebar").animate({ marginTop:0 },400);
			$(".scroll").animate({ height:225 },400);
			$(".navigation").show();
			showVideos();
		});
	}
	else if (to=="galleries") {
		$("#flGalleryScroll").fadeOut(400, function(){
			$("#flGalleryScroll").remove();
			$(".scroll").animate({ height:225 },200);
			$("#mainContent").animate({ marginTop:0 },200);
			$("#sidebar").animate({ marginTop:0 },200);
			$(".navigation").show();
			showGalleries();
		});
	}
}
/********
Galleries
*********/
var ngli = 0;
function showGalleries () {
	clearInterval(bz);
	videoadded = false;
	$("#panelContainer").html("<div class='video-loader'><span id='loader-text'><img style='position:relative' src='/themes/Sunswift/images/loader.gif' /></span></div>");
    $(".video-loader").animate({'opacity':1},200);
	$("#panelContainer").append('<div id="galleries"><ul></ul><div class="slider"><div class="handle"></div></div></div>');
	ngli = 0;
	$.getJSON("/galleries-json",
        function(data){
          $.each(data.galleries, function(i,gallery){
			ngli++;
            addGalleryLi(gallery.url,gallery.thumb,gallery.title);
		});
		var w = ngli*240;
		//alert(ngli2);	
		//alert($("#panelContainer ul li").size());
	    if (w<780) w = 780;
	    $("#galleries ul").width(w);
	
		if (w>780) makeslider('#galleries',ngli);	
		else {$(".slider").remove(); }
		
		if (navigator.appName=="Opera") {
			$("#galleries ul li a img").load(function() {
				makeOverlays (".galthumb");
				$(".video-loader").animate( {'opacity':0},300,function(){$(".video-loader").remove();});
			});
		}
		else {
			$("#galleries ul li a img").load(function() {
				makeOverlays (".galthumb");
				$(".video-loader").animate( {'opacity':0},300,function(){$(".video-loader").remove();});
			});			
		}
	});
}
function showGallery (g) {
	$("#panelContainer").html("<div id='flGalleryScroll'></div>");
	h = 413+"px";
	$(".navigation").hide();
	$(".scroll").animate({ height:h },400);
	$("#flGalleryScroll").animate({ height:h },400,function(){
		$("#flGalleryScroll").css("display","block");
		makeBackButton("galleries");
	});
	var adjh = (downbuffer+413)+"px";
	$("#mainContent").animate({ marginTop:adjh },300);
	$("#sidebar").animate({ marginTop:adjh },300);
	$("#pausedSliderOverlay").css("display","none");
	$("#panelContainer").css("height","413px");
	$("#flGalleryScroll").flash({
		swf:'http://www.sunswift.com/themes/Sunswift/lib/scroller.swf',
		wmode: "transparent",
		width: 780,
		height: 413,
		flashvars: {
	        xml_file: "http://www.sunswift.com/images-xml?g="+g //CHANGE TO SUNSWIFT.COM
		},
	});	
}
function addGalleryLi (url,thumb,title) {
	$("#galleries ul").append("<li><div onClick=\"javascript:showGallery('"+url+"');\"><span class='thumb_overlay'>"+title+"</span></div><a href=\"javascript:;\" onClick=\"javascript:showGallery('"+url+"');\"><img class='galthumb' src='"+thumb+"' width='200' style='position:relative' alt='"+url+"'  /></a></li>");
	$(".galthumb:last").ready(function() {
		$(".galthumb:last").reflect().css("position", "relative");
	});
}
function makeOverlays (thumb) {
	var VLToggle=0;
	$(thumb).each(function() {
		// Get the thumbnail data
		var li_top = $(this).children(".reflected:first").css("top")+"px";
		var li_left = $(this).children(".reflected:first").css("left")+"px";
		var img_width = $(this).children(".reflected:first").width()+"px";
		var img_height = $(this).children(".reflected:first").height()+"px";
		// Set the css for the div
		$(this).parent().siblings("div:first").css({
			"top"		:li_top,
			"left"		:li_left,
			"width"		:img_width,
			"height"	:img_height
		}).mouseenter(function(){
			if (VLToggle==1) return; 
			else {
				$(this).animate( {'opacity':0.6},200);
				VLToggle=1;
			}
		}).mouseleave(function() { 
			$(this).animate( {'opacity':0},200);
			VLToggle=0;
		});
		// Figure out how high to put the span with the title on the thumbnail
		// You have to run this after the previous command has executed, so that the div has constrained width,
		// We need that to get the span's height properly
		var span = $(this).parent().siblings("div:first").children("span");
		var tHeight = $(this).height() - $(this).children("canvas").height();
		var spanheight = span.height();
		var stop = ((tHeight/2)-(spanheight/2))+"px";
		span.css("top",stop);
	});
}

function IVY () {
	var xk=$(window).scrollTop()+"px";
	var xh=(10*$(window).height())+"px";
	$(document.body).append("<div id='the-void'></div>");
	$("#the-void").css("display","none");
	$("#the-void").css("height",xh);
	$("#the-void").fadeIn(2000,function() {
		 window.location="/ivy?from=home";
		/*
		$("body").addClass("body_fadeOutEverything");
		$("body").html("");
		scroll(0,0);
		makeIvyLaunch();
		*/
	 });
}
var GLToggle=0;

var video_id = 4632707;
var moogaloop = false;
var preload_data = null;

function vimeo_player_loaded(swf_id) {
	moogaloop = document.getElementById(swf_id);
	moogaloop.api_changeColor("000000");
	$("#moogaloop").ready(function(){moogaloop.api_play();});	
	moogaloop.api_addEventListener('onProgress', 'vimeo_on_progress');
	moogaloop.api_addEventListener('onFinish',   'vimeo_on_finish');
	moogaloop.api_addEventListener('onPause',    'vimeo_on_finish');

	$.get("/ivy?clean=1", function(data){
	  preload_data = data;
	});
}

var hasrun=0;
function vimeo_on_progress(time, swf_id) {
	//document.getElementById('progress').innerHTML = time;
	if (hasrun==0) {
		if (time>0) {
			$("#videocontainer_overlay").fadeOut(750,function() {$("#videocontainer_overlay").remove();});
			hasrun=1;
			//alert("hasrun");
		}
	}
}
function vimeo_on_finish(swf_id) {
	if (preload_data!=null){
		$("#videocontainer").fadeOut(500,function(){
		//$("#videocontainer_overlay").remove();
		$("body").html('<div id="videocontainer_overlay" class="videocontainer_overlay">&nbsp;</div>').append(preload_data).removeClass("body_fadeOutEverything").removeClass("oneColFixCtrHdr").addClass("body_ivylaunch");
		$("#videocontainer_overlay").fadeOut(2000);	
		});
	}
}
function makeIvyLaunch () {
	// Run the javascript when the page is ready
	var swf_id = 'moogaloop';
	$("body").css("text-align","center");
	$("body").html('<div id="videocontainer_overlay" class="videocontainer_overlay"><img style="margin-top:120px" src="/themes/Sunswift/images/ivy_loader.gif" alt="Loading!" /><br /><br /><a href="/ivy" style="text-decoration:none;color:white; font-size:9px;">You are being redirected. Click here to speed things up.</a></div><div id="videocontainer" class="videocontainer_class"><div id="moogaloop"></div></div>');
 	/*
	var flashvars = {
        clip_id: 6017824,
        show_portrait: 0,
        show_byline: 0,
        show_title: 0,
		js_api: 1, // required in order to use the Javascript API
		js_onLoad: 'vimeo_player_loaded', // moogaloop will call this JS function when it's done loading (optional)
		js_swf_id: 'moogaloop' // this will be passed into all event methods so you can keep track of multiple moogaloops (optional)
    };
	var params = {
		allowscriptaccess: 'always',
		allowfullscreen: 'false',
		wmode: 'transparent',
	};
	var attributes = {};
	swfobject.embedSWF("http://vimeo.com/moogaloop.swf?autoplay=1", swf_id, "640", "352	", "9.0.0","expressInstall.swf", flashvars, params, attributes);
	*/
}
function openShadowbox(content, player, title, gallery){
    Shadowbox.open({
        content:    content,
        player:     player,
        title:      title
    });
	
}
		

