var is_logged_in = false;
var gallery = null;
var nav = $('#sets');
//var current_photo_index;
var first_load = true;
var url = window.location.href;
var baseURL = url.substring(0, url.indexOf('/', 14) ) + "/";
var hash = window.location.hash;
var index_of_hash = url.indexOf(hash) || url.length;
var hashless_url = url.substr(0, index_of_hash);
var thumb_adjust_height = 50;
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isiPhone = isiPhone();

$("#twitter").tooltip({ effect: 'toggle', offset: [ 75, 0 ] });	
$("#facebook").tooltip({ effect: 'toggle', offset: [ 75, 0 ] });	
$("#blog").tooltip({ effect: 'toggle', offset: [ 75, 0 ] });	
$("#email").tooltip({ effect: 'toggle', offset: [ 75, -50 ] });

// set user theme and prefs
//$('#photos').css( 'background-color', $("#background_color").html() );
$(document.body).css( 'background', $("#background_color").html() );
$(document.body).css( 'font-family', $("#font").html() );
$(document.body).css( 'color', $("#font_color").html() );

/*
$('#options li a').css( 'color', $("#font_color").html() );
$('#options li a').css( 'background', $("#collection_nav_color").html() );
$('#sets li a').css( 'background', $("#set_nav_color").html() );
$('#sets li a').css( 'color', $("#font_color").html() );
*/

$('.collections li a').css( 'color', $("#font_color").html() );
$('.collections li a').css( 'background', $("#collection_nav_color").html() );
$('.sets li a').css( 'background', $("#set_nav_color").html() );
$('.sets li a').css( 'color', $("#font_color").html() );


/*
$('.tooltip').css( 'background-color', $("#background_color").html() );
$('.tooltip').css( 'color', $("#font_color").html() );
*/

$('body').click(function(e) {
	$('.collections').closeMenu();
});


$(window).resize(function() {
	if( !isiPad ) reset_view();
});
	
function reset_view()
{
	//$("#photos").css({ 'height': $(window).height(), 'width': $(window).width() });
	gallery.rescale( $(window).width(), $(window).height() );
	$('.galleria-thumbnails-container').css({ 'top': $(window).height() - thumb_adjust_height});
}

function isiPhone(){
    return (
        //Detect iPhone
        (navigator.platform.indexOf("iPhone") != -1) ||
        //Detect iPod
        (navigator.platform.indexOf("iPod") != -1)
    );
}

// click on set
$('.sets li a').click(function() {
    load_set( $(this).attr('id') );
    return false;
});

// load a new set
function load_set( set_id )
{
	// show loader
	showLoading( 1 );

	// clear out gallery
	gallery.splice( 0, gallery.getDataLength() );
	
	// fade out gallery
	//gallerytransition( 0 );
	
	// hide the nav
	//nav.isotope({ filter: 'none' });
	$('.collections').closeMenu();
	
	$.post("/photos/get_set_photos/", { set_id : set_id },
	function( data )
	{
		data = jQuery.parseJSON( data );
	
		// loop new photos
		$.each(
			data.photos_array,
			function( intIndex, objValue )
			{
				// add new photo thumbs
				gallery.push({ image: objValue.large, thumb: objValue.thumb });
			}
		);
		
		// hide loader
		showLoading( 0 );
		
		// change hash
		//log( 'url: ' + url );
		//log( 'hashless_url: ' + hashless_url );
		window.location = hashless_url+"#/set/" + set_id;
		
		// load first one
		gallery.show( 0 );
		
	});
	
}

function get_hash_item( hash_item )
{

	// parse the data
	//var elements = jHash.root().split('/');
	
	var elements = location.hash.split('/');

	// the Object that will have the data
	var hash_data_obj = new Object();

	// do a for loop
	for( i = 0; i < elements.length; i++ )
	{
		hash_data_obj[elements[i]] = elements[i+1];
	}
	
	hash_item = hash_data_obj[ hash_item ];
	
	//log( 'hash_item = ' + hash_item );
	
	if( hash_item )
	{
		return hash_item;
	}
	else
	{
		return "";
	}
}

function showLoading( on )
{
	if( on == 1 )
	{
		$("#loader").html( '<img src="/images/ajax-loader.gif">' );
	}
	else
	{
		$("#loader").html( '' );
	}
}

function gallerytransition( opac )
{
	$('.galleria-container').animate({
		opacity: opac
	}, 300, function() {
		// Animation complete.
	});
}



// nav
$('#filter a').click(function() {
    var filterName = $(this).attr('data-filter');
    nav.isotope({
        filter: filterName
    });
    return false;
});

// switches selected class on buttons
$('#options').find('.option-set a').click(function() {
    var $this = $(this);

    // don't proceed if already selected
    if (!$this.hasClass('selected')) {
        $this.parents('.option-set').find('.selected').removeClass('selected');
        $this.addClass('selected');
    }

});

/*
nav.isotope({
	filter: 'none',
	layoutMode: 'straightDown',
	animationOptions: {
		duration: 400,
		easing: 'linear',
		animationEngine: 'jquery',
		queue: false
	}
});
*/

/*

<ul class="menu [optional class] [optional class]">
<li><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
...
...
</ul>
// This item is open at page load time
<li class="expand"><a href="#">Sub menu heading</a>
<ul>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
<li><a href="http://site.com/">Link</a></li>
...
...
</ul>
...
...
</ul>
*/

jQuery.fn.closeMenu = function() {  
    return this.each(function(){
        var theMenu = $(this).get(0);
        $('.sets', this).hide();
        $('li.expand > .sets', this).show();
        $('li.expand > .sets', this).prev().addClass('active');
        
});
};

jQuery.fn.initMenu = function() {  
    return this.each(function(){
        var theMenu = $(this).get(0);
        $('.sets', this).hide();
        $('li.expand > .sets', this).show();
        $('li.expand > .sets', this).prev().addClass('active');
        $('li a', this).click(
            function(e) {
                e.stopImmediatePropagation();
                var theElement = $(this).next();
                var parent = this.parentNode.parentNode;
                if($(parent).hasClass('noaccordion')) {
                    if(theElement[0] === undefined) {
                        window.location.href = this.href;
                    }
                    $(theElement).slideToggle('normal', function() {
                        if ($(this).is(':visible')) {
                            $(this).prev().addClass('active');
                        }
                        else {
                            $(this).prev().removeClass('active');
                        }    
                    });
                    return false;
                }
                else {
                    if(theElement.hasClass('sets') && theElement.is(':visible')) {
                        if($(parent).hasClass('collapsible')) {
                            $('.sets:visible', parent).first().slideUp('normal', 
                            function() {
                                $(this).prev().removeClass('active');
                            }
                        );
                        return false;  
                    }
                    return false;
                }
                if(theElement.hasClass('sets') && !theElement.is(':visible')) {         
                    $('.sets:visible', parent).first().slideUp('normal', function() {
                        $(this).prev().removeClass('active');
                    });
                    theElement.slideDown('normal', function() {
                        $(this).prev().addClass('active');
                    });
                    return false;
                }
            }
        }
    );
});
};

$('.collections').initMenu();


// calculate image margin
var max_scale = Number( $("#embiggen").html() );
if( Number( $("#embiggen").html() ) == 1 )
{
	max_scale = .8;
	//thumb_adjust_height = 100;
}
else
{
	max_scale = 1.5;
	//thumb_adjust_height = 50;
}

//log( "touch: " + Galleria.TOUCH );
var tansition_type = 'flash';
if( Galleria.TOUCH ) tansition_type = 'slide';
Galleria.loadTheme('/js/themes/classic/galleria.classic.js');
$('#photos').galleria(
{
    transition: tansition_type,
    debug: false,
    clicknext: false,
    preload: 2,
    transitionSpeed: 500,
    show_counter: false,
    fullscreenDoubleTap: false,
    thumbQuality: false,
    maxScaleRatio: max_scale,
    thumb_crop: "height",
    extend: function() {
    
    	gallery = this;
    	
    	this.attachKeyboard({
		    left: this.prev, // applies the native prev() function
		    right: this.next
		});
    
        this.bind(Galleria.IMAGE, function(e) {
        	/*
current_photo = e.imageTarget;
        	current_photo_index = e.index;
        	log( "current_photo_index: " + current_photo_index );
        	log( "current_photo: " + current_photo );
*/
        	
        	//$(".galleria-container img").css( 'height', $(window).height()/2 );
        	
        	if( first_load )
        	{
	        	if( get_hash_item( "set" ) != "" )
				{
					load_set( get_hash_item( "set" ) );
				}
				else
				{
					load_set( $('#first_set_id').html() );
				}
				
				/*
if( Number( $("#embiggen").html() ) == 1 )
				{
					$('.galleria-container').css( 'top', '50' );
					$('.galleria-thumbnails-container').animate({
						top: $('#photos').height() - thumb_adjust_height
					}, 1, function() {
						// Animation complete.
					});
				}
*/
        	}
        	first_load = false;
        	
        });
    }
});


if( $("#google_analytics").html() != "" )
{

// google analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', $("#google_analytics").html()]);
_gaq.push(['_trackPageview']);

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

}

// show photos
$('#showcase').show();
