$.fn.revealimage = function () {
    $(".content").fadeTo(1000, 0);
    if ( !$("#wrapper").hasClass("case-study")) {
        $("#background img").fadeTo(1000, 1);
    }
    $("h1").fadeTo(1000, 0);
    $("#reveal-image > a").empty();
    $("#reveal-image > a").prepend("Reveal text");
    $("#navigation-toggle > a").click();
    
    /*var $backgroundImage = $("#background img");
    var $background = $("#background");
    $backgroundImage.css("width", 'auto');
    $background.css("width", 'auto');
    $backgroundImage.css("margin-left", "auto");
    $backgroundImage.css("margin-right", "auto");
    
    $backgroundImage.animate({
        top: "0px"
    }, 1000 );
    $backgroundImage.animate({
        height: "100%"
    }, 1000 );

    $background.animate({
        height: "100%"
    }, 1000 );
    */

    //$background.css("height", '100%');
    
    //$backgroundImage.css("height", '100%');

    //$backgroundImage.css("top", '0px');
};

$.fn.unrevealimage = function () {
    $(".content").fadeTo(1000, 1);
    if ( !$("#wrapper").hasClass("case-study")) {
        $("#background img").fadeTo(1000, 0.5);
    }
    $("h1").fadeTo(1000, 1);
    $("#reveal-image > a").empty();
    $("#reveal-image > a").prepend("Reveal image");
};

$.fn.loadrevealimage = function () {
    $("#reveal-image").removeClass("disabled");
    $("#reveal-image").fadeTo(1000, 1);
    $("#reveal-image > a").toggle(
        function (event) {
            $("#background").revealimage();
            event.preventDefault();
        },
        function (event) {
            $("#background").unrevealimage();
            event.preventDefault();
        }
    );
};


// function to close navigation
$.fn.closenav = function () {
    $(this).animate({
        bottom: 0 - $(this).outerHeight()
    }, 750);	
    $("#navigation-toggle > a").empty();
    $("#navigation-toggle > a").prepend("Explore");
    $("#navigation-toggle > a").addClass("closed");
    $("#navigation-toggle > a").removeClass("open");
};

// function to open navigation
$.fn.opennav = function () {
    $(this).animate({
        bottom: 0
    }, 750);
    $("#navigation-toggle > a").empty();
    $("#navigation-toggle > a").prepend("Close");
    $("#navigation-toggle > a").addClass("open");
    $("#navigation-toggle > a").removeClass("closed");		
};

// pause function
$.fn.pause = function (n) {
    return this.queue(function () {
        var el = this;
        setTimeout(function () {
            return $(el).dequeue();
        }, n);
    });
};


$.fn.unblur = function(n){
    $(this).pause(3000);
    return this.queue(function(){
        var $el = $(this);
        var style = $el.css("text-shadow");
        _unblur = function( $el, style ){
            //console.log(style);
            var matches = $el.css("text-shadow").match(/[1-9]\d*px/g);
            //console.log( matches && matches.length );
            if( matches && matches.length > 0){
                $.each(matches, function(index, value) {
                    //console.log("index", index, "value", value);
                    var newValue = parseInt(value) - 1;
                    style = style.replace(value, newValue + "px");
                });
                $el.css("text-shadow", style);
                setTimeout(function(){
                    _unblur($el, style);
                }, n);
            }
            else{
                $el.removeClass("content-blur").css("text-shadow", "");
                return $el.dequeue();
            }
        };
        _unblur($el, style);
        
    });
    //return $this;
};

var resizeWindow = function(){
    
    var $backgroundImage = $("#background img");
    var $background = $("#background");
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    var windowRatio = parseFloat(windowHeight) / parseFloat(windowWidth);
    var imageHeight = parseInt($backgroundImage.height());
    var imageWidth = parseInt($backgroundImage.width());
    var imageRatio = parseFloat(imageHeight) / parseFloat(imageWidth);
    //imageHeight -= parseInt($(background).attr("top"));
    //if (!$("#wrapper").hasClass("case-study")) {
    //    imageHeight = imageHeight + 250;
    //}
    //var extraPercent = 100 + ((imageHeight / 100) * 250);
    var $blurredImage = $("#blurred-image");

    var setFullHeight = function(){
        $background.css("height", '100%');
        $background.css("width", 'auto');
        $backgroundImage.css("height", '100%');
        $backgroundImage.css("width", 'auto');
        if($blurredImage.length > 0){
            $blurredImage.css("height", '100%');
            $blurredImage.css("width", 'auto');
        }
    }
    
    var setFullWidth = function(){
        $background.css("width", '100%');
        $background.css("height", 'auto');
        $backgroundImage.css("width", '100%');
        $backgroundImage.css("height", 'auto');
        if($blurredImage.length > 0){
            $blurredImage.css("width", '100%');
            $blurredImage.css("height", 'auto');
        }
    }
    
    
    
    if( windowWidth >= windowHeight ){
        if( imageWidth >= imageHeight ){
            // case 1
            //console.log( "ih: " + imageHeight + " - wh: " + windowHeight);
            if( imageWidth >= windowWidth ){
                // height = 100%
                setFullHeight();
            }
            else{
                // width = 100%
                setFullWidth();
                
            }
        }
        else{
            // case 2
            // width = 100%
            setFullWidth();
        }
    }
    else{
        if( imageWidth >= imageHeight ){
            
            // case 3
            // height = 100%
            setFullHeight();
        }
        else{
            // case 4
            /*if( imageHeight == windowHeight && imageWidth > windowWidth ){
                // height = 100%
                setFullHeight();
            }
            else if( imageWidth == windowWidth && imageHeight > windowHeight ){
                // width = 100%
                setFullWidth();
                //alert("set the full height"); 
            }
            else */
            if( imageHeight == windowHeight ){
                // width = 100%
                setFullHeight();
            }else if( imageHeight > windowHeight ){
                // width = 100%
                setFullWidth();
            }
            else{
                // height = 100%
                setFullHeight();
            }
        }
    } 
}



$(document).ready(function(){
    
    $('.backgroundImg').hide();
    $('.backgroundImg').onImagesLoad({
        selectorCallback: imageLoad
    });

	// hide tagline
	$(".content-tagline p").hide();
    $(".content").css("margin-bottom", "30px");
    
    //	background animation
    if ($("#wrapper").hasClass("case-study")) {
        // hide the content div
        var $content = $(".content");
        $content.hide();
        $content.fadeTo(0, 0);
    }
    
    // resize window, lets attach the event
    $(window).resize(function(){
        resizeWindow();
    });
    
    //  insert 'explore' link in to navigation
	$nav = $("#navigation");
    $nav.prepend("<div id=\"navigation-toggle\"><a href=\"#\">Explore</a></div>");
	
	$("#navigation-toggle > a").toggle(
		function (event) {
			$nav.opennav();
			event.preventDefault();
		},
		function (event) {
			$nav.closenav();
			event.preventDefault();
		}
	);
    
        //	reveal image function
    var $reveal_image = $("#reveal-image");
	$reveal_image.addClass("disabled");
	$reveal_image.fadeTo(500, 0.25);
	$("#reveal-image > a").click(function(event){
		event.preventDefault();
	});
    
    
    
    
}).error(function(){
    //console.log("err");
});


/*************
 *
 * Facebook connect from here on in
 *
 *
 ***************/
// Facebook connect variables
//var apikey = "8f3b320268226150753e070c6312c065"; // staging test api key
var apikey = "48094f50d6f315df1ec0dd762d42d3c0";
var xd = "/connect/xd_receiver.htm";
var api = null;

var callback = function(){alert("finished!");};
var animating = false;
$(document).ready(function(){
    /*
     * Facebook Connect bit by Edd
     */
    
    // set up the document:
    // hide the user details and logout button
    // make sure we have an API object set up
    // check if we need to show or hide the user details
    $("#user-details").hide();
    
    FB_RequireFeatures(["Api"], function(){
        FB.init(apikey, xd);
        api = FB.Facebook.apiClient;
        showHideFBElements();
    });
    
	//hide navigation
	$("#navigation").css("bottom",0 - $("#navigation").outerHeight());
	//	$("#navigation").closenav();
});


var showHideFBElements = function(){
    api.users_getLoggedInUser(function(result, exception){
        if( result !== null){
            $(document).ready(function(){
                $("#user-details").show();
                $("#login-control").hide();
            });
        }
        else{
            $(document).ready(function(){
                $("#user-details").hide();
                $("#login-control").show();
            });
        }
    });
}

var loginCallback = function(){
    showHideFBElements();
    setTimeout(function(){ document.location = "/facebook"}, 5000)    
}


var postFeed = function(){
    FB_RequireFeatures(["Connect"], function(){
		var attachment = {
			'name': 'Check out the Sightsavers Rankin campaign!',
			'href': 'http://rankin.sightsavers.org/',
			'caption': '{*actor*} loves Rankin\'s amazing images and is flabbergasted by the fact that women are twice as likely as men to be blind.',
			'media': [{
				'type': 'image',
				'src': 'http://rankin.sightsavers.org/img/issues/trachoma_image_thumb.jpg',
				'href': 'http://rankin.sightsavers.org/'
			}]
		};
		var action_links = [{
			"text": "If you care, share",
			"href": "http://rankin.sightsavers.org/"
		}];
		FB.Connect.streamPublish(
			"",						// user_message
			attachment,				// attachment
			action_links,			// action_links
			null,					// target_id
			"If you care, share",	// user_message_prompt
			updateStats,			// callback
			false,					// auto_publish
			null					// actor_id
		);
	});
}

var updateStats = function(){
    api.users_getLoggedInUser(function(result, exception){
        if( result !== null){
            $.post("/stats/update/", "data[Stat][uid]=" + result,
                function(data){
                      updateStatsResponse(data);
                    }, "text");
        }
    });
}

var updateStatsResponse = function(data){
    //alert(data);
}


var imageLoad = function ( $selector ) {
    resizeWindow();

    var $backgroundImage = $selector;

    //	background animation
    if ($("#wrapper").hasClass("case-study")) {
        //  case study animation
        var originalImagePath = $backgroundImage.attr("src");
        var blurredImagePath = originalImagePath.replace(".jpg","_blurred.jpg");
        
        //create a new element for the the blurred image, no src given yet
        $("#background").prepend("<img id=\"blurred-image\" alt=\"\" />");
        var $blurredImage = $("#blurred-image");
        $blurredImage.hide();
        // resize the window so the blurred image becomes the right size
        resizeWindow();
        // bind the load funtion
        $blurredImage.load(function () {
            $blurredImage.show();
            $backgroundImage.show();
            //	$backgroundImage.fadeTo(0, 0);
            
            $blurredImage.fadeTo(3000, 0);
            
            //	$backgroundImage.fadeTo(10000, 1);
        });
        // now set the source becuase we have hidden it and set the load
        // we are now safe to show it! :D
        $blurredImage.attr("src", blurredImagePath);
        var $content = $(".content");
        $content.show();
        $content.pause(2500).fadeTo(1500, 0.8);
        $backgroundImage.loadrevealimage();

    } else {

        //  show tagline and other content text
        var i=0;
        var paras, $parasElement;
        var $ct = $(".content-tagline p");
        var $aqa = $("#artist-qa").children();
        var $fb = $("#larger-content");
        
        if ($ct.length > 0){
            paras = $ct.length;
            $parasElement = $ct;
        }
        else if ($aqa.length > 0){
            paras = $aqa.length;
            $parasElement = $aqa;
        }
        else if ($fb.length > 0){
            paras = $fb.length;
            $parasElement = $fb;
        }
        
        if ($parasElement){
            $parasElement.hide();
            $parasElement.fadeTo(0,0);
        }
        
        
        var bgImgPause = ""; //500; //adjusted to 5500 for the flash header
        var $title = $('#title');
        if( $title.length > 0){
            bgImgPause = "5500";
        }
        else{
            bgImgPause = "500";
        }
        //	homepage animation
        
        var bgImgFade = 2500;
        var bgImgPause2 = 500;
        var bgImgAnimate = 1500;
        var bgImgFade2 = 1500;
        var bgTotal = bgImgPause + bgImgFade + bgImgPause2 + bgImgAnimate + bgImgFade2;

        $backgroundImage.hide();
        $backgroundImage.fadeTo(0, 0);
        animating = true;

        $backgroundImage.show();
        $backgroundImage.queue(function(){

            //  raise image to full opacity
            //  $(this).fadeTo(3000, 1);
            $backgroundImage.pause(bgImgPause).fadeTo(bgImgFade, 1)
                .queue(function(){
                    //  pan image upwards
                    $backgroundImage.animate({
                        top: "-350px"
                    }, bgImgAnimate )
                    
                    .fadeTo(bgImgFade2, 0.50) //  fade image back
                        .queue(function () {
                            $backgroundImage.loadrevealimage();
                            $backgroundImage.dequeue();
                        });
                    $backgroundImage.dequeue();
                });
            $backgroundImage.dequeue();
        })
        .queue(function(){
            animating = false;
            $backgroundImage.dequeue();
        })//.pause(3000)
        .queue(function(){
            $parasElement.pause(3000).each(function(){
                //console.log("each");
               $(this).show().pause(250).fadeTo(750, 1);
            });
            $backgroundImage.dequeue();
        });
    };
};