var currentfolder = '';
var currentsect = '';
var gallery;	
var autoselect;
var imgfolder;
var instore;
var galleryoptions = {
	delay:                     4000, // in milliseconds
	numThumbs:                 6, // The number of thumbnails to show page
	preloadAhead:              0, // Set to -1 to preload all images
	enableTopPager:            false,
	enableBottomPager:         false,
	maxPagesToShow:            0,  // The maximum number of pages to display in either the top or bottom pager
	galleryContainerSel:	   '#gallery',
	imageContainerSel:         '#slideshow', // The CSS selector for the element within which the main slideshow image should be rendered
	controlsContainerSel:      '#controls', // The CSS selector for the element within which the slideshow controls should be rendered
	captionContainerSel:       '', // The CSS selector for the element within which the captions should be rendered
	loadingContainerSel:       '#loading', // The CSS selector for the element within which should be shown when an image is loading
	renderSSControls:          false, // Specifies whether the slideshow's Play and Pause links should be rendered
	renderNavControls:         false, // Specifies whether the slideshow's Next and Previous links should be rendered
	playLinkText:              'Play',
	pauseLinkText:             'Pause',
	prevLinkText:              'Previous',
	nextLinkText:              'Next',
	nextPageLinkText:          'Next &rsaquo;',
	prevPageLinkText:          '&lsaquo; Prev',
	enableHistory:             false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
	enableKeyboardNavigation:  false, // Specifies whether keyboard navigation is enabled
	autoStart:                 false, // Specifies whether the slideshow should be playing or paused when the page first loads
	syncTransitions:           false, // Specifies whether the out and in transitions occur simultaneously or distinctly
	defaultTransitionDuration: 1000, // If using the default transitions, specifies the duration of the transitions
	onSlideChange:             undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... }
	onTransitionOut:           undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... }
	onTransitionIn:            undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... }
	onPageTransitionOut:       undefined, // accepts a delegate like such: function(callback) { ... }
	onPageTransitionIn:        updatepages, // accepts a delegate like such: function() { ... }
	onImageAdded:              undefined, // accepts a delegate like such: function(imageData, $li) { ... }
	onImageRemoved:            undefined  // accepts a delegate like such: function(imageData, $li) { ... }
}
	
$(function() {
		   
	$('.advance-link').click(function() {
		alert('Handler for .change() called.');
	});

	$('.thumbarrow.prev').click(function(e) {
		if(currentsect == 'general') gallery.firstTime = true;
		gallery.previousPage();
		e.preventDefault();
	});

	$('.thumbarrow.next').click(function(e) {
		if(currentsect == 'general') gallery.firstTime = true;
		gallery.nextPage();
		e.preventDefault();
	});

	$('.close').click(function(e) {
		gallery.hideImage();
		showshare(true);
		showtwitter(true);
		showemail(true);
		e.preventDefault();					   
	});
	
	if(autoselect) {
		loadgallery(imgfolder +  $('.singleShow:first a').attr('rel'));
	}
	
	$('#shareemail').validate({
		messages:{
            toname: "<span class=\"pink\">+ </span>Enter your name.<br/>", 
            fromname: "<span class=\"pink\">+ </span>Enter your friend's name.<br/>", 
            toemail: "<span class=\"pink\">+ </span>Enter your friend's email address.<br/>",
			fromemail: "<span class=\"pink\">+ </span>Enter your email address.<br/>"
        },
		errorLabelContainer: $("div#error"),
		onfocusin: null,
		onfocusout: null,
		//onkeyup: null,
		onclick: null,
		highlight: null,
		unhighlight: null
	});
	
	$('#shareemail').submit(share);
	
});

var errorText = 'Please fill all fields';
var thanksText = '<span class="pink"+ </span>Thanks for sharing, little monster.';

function share(event) {
	event.preventDefault();
	$('#shareemail #submit').attr('disabled', 'disabled');
	var fromname = $('#fromname').val();
	var fromemail = $('#fromemail').val();
	var toname = $('#toname').val();
	var toemail = $('#toemail').val();
	var file = $('.advance-link img').attr('src');//$('#emailimage').val();
	var dataString = 'action=gallery_send_email&fromName='+fromname+'&fromEmail='+fromemail+'&toName='+toname+'&toEmail='+toemail+'&file='+file;
		
	if($('#shareemail').valid()) {
		$("#div#error").html('');
		$.ajax({
			type: "GET",
			url: "_scripts/sendToFriend.php",
			data: dataString,
			success: function() {
				$('#shareemail #submit').removeAttr('disabled');
				$('#email #error').html(thanksText).css('display', 'block');
				$('#shareemail input.required').val('')
			}
		});
	} else $('#shareemail #submit').removeAttr('disabled');
	
	return true;
}

function updatepages() {
	
	this.css('display', 'block');		
	
	var prevPageLink = $('.thumbarrow.prev').css('visibility', 'hidden');
	var nextPageLink = $('.thumbarrow.next').css('visibility', 'hidden');
	
	var currpage = this.getCurrentPage() + 1;
	if(currpage < 10) currpage = '0' + currpage;
	
	var totalpages = this.getNumPages();
	if(totalpages < 10) totalpages = '0' + totalpages;
	
	if (this.displayedPage > 0)
		prevPageLink.css('visibility', 'visible');

	var lastPage = this.getNumPages() - 1;
	if (this.displayedPage < lastPage)
		nextPageLink.css('visibility', 'visible');

	
	$('#pagecount').html(currpage + ' | ' + totalpages);
	
}

function loadgallery(folder) {
	
	if(gallery != null) gallery.pause();
	
	// CLEAR OLD IMAGE
	$('#slideshow').html('');
	
	$('#galleryNav').css('visibility', 'visible');
		
	var sects = folder.split('/');
	$('.singleShow.current').removeClass('current');
	$('#' + sects[sects.length - 1] + '.singleShow').addClass('current'); 
	
	var info = sects[sects.length - 1];
	var data = info.split('_');
	
	$('#nowPlayingMonth').html(month(data[1]));
	$('#nowPlayingDay').html(data[2]);
	$('#nowPlayingCity').html(fixname(data[0]));
				
	//loadsection(folder + '/featured/');
	
		
	$('#subnav').css('visibility', 'visible');
	$('#gallery_featured').attr('href', 'javascript:loadsection(\''+folder + '/featured/\')');
	$('#gallery_general').attr('href', 'javascript:loadsection(\''+folder + '/general/\')');
	$('#gallery_polaroid').attr('href', 'javascript:loadsection(\''+folder + '/polaroid/\')');
		
	$.get("gallery/photos.inc.php", 'foldercheck=' + folder, foldercheck);
}

function foldercheck(data) {
	
	var obj = eval('(' + data + ')');
	
	//console.log($('.polaroid'));
		
	if(obj.haspolaroid == 'true') $('.polaroid').css('visibility', 'visible');
	else $('.polaroid').css('visibility', 'hidden');
	
	loadsection(obj.folder + 'featured/');	
}

function loadsection(folder) {
	
	if(gallery != null) gallery.pause();
	
	currentfolder = folder;
		// SET THE HIGHLIGHTED SECT
	var sects = folder.split('/');
	currentsect = sects[3];
	
	$('.sects.active').removeClass('active');
	$('#gallery_' + currentsect).addClass('active');
		
	// SET CORRECT GALLERY OPTIONS
	if(currentsect == 'featured') {
		galleryoptions['numThumbs'] = 6;
		galleryoptions['onlyThumbs'] = false;
		galleryoptions['autoStart'] = true;
		galleryoptions['firstTime'] = false;
		$('#nowPlayingTitle').html('FEATURED MONSTERS');
	} else if(currentsect == 'general') {
		gallery.pause();
		gallery.hideImage();
		galleryoptions['numThumbs'] = 30;
		galleryoptions['onlyThumbs'] = true;
		galleryoptions['autoStart'] = false;
		galleryoptions['firstTime'] = true;	
		$('#nowPlayingTitle').html('MONSTER GALLERY');
	} else if(currentsect == 'polaroid') {
		galleryoptions['numThumbs'] = 6;
		galleryoptions['onlyThumbs'] = false;
		galleryoptions['autoStart'] = true;
		galleryoptions['firstTime'] = false;
		$('#nowPlayingTitle').html('POLAROID MONSTERS');	
	}
	
	$.get("gallery/photos.inc.php", 'photos=' + folder + '&url=' + folder, loaded);

}

function loaded(data) {
	
	// We only want these styles applied when javascript is enabled
	//$('div.navigation').css({'width' : '300px', 'float' : 'left'});
	//$('#gallery').css('display', 'block');
		
	// Clear any old images
	$('#thumbHolder').html(data);	
		
	gallery = $('#gallery').galleriffic(galleryoptions);
		
	gallery.refresh();
	
	// ADJUST GALLERY DISPLAY
	if(currentsect == 'featured' || currentsect == 'polaroid') {
		$('ul.thumbs').addClass('featured');//.css('float', 'right');
		$('div#thumbs').css('width', 'auto');
		/*$('#gallery').css('position', 'relative');*/
		$('.slideshow-container').removeClass('general');
	} else if(currentsect == 'general') {
		$('ul.thumbs.featured').removeClass('featured');//.css({'float':'left', 'margin-left':'5px'});
		$('div#thumbs').css('width', '300px');
		/*$('#gallery').css('position', 'absolute');*/
		$('.slideshow-container').addClass('general');
	} 
	
}		

/*****
	
	GALLERY SHARING
	
*****/

function showshare(hide) {
			
	if($('#share').css('visibility') == 'visible' || hide == true) {
		$('#share').css('visibility', 'hidden');
		showtwitter(true);
		//showfacebook(true);
	} else {
		if(gallery != null) gallery.pause();
		
		showemail(true);
		showtwitter(true);
		//showfacebook(true);
		// LOAD SHARE LINKS
		
		//console.log($('.advance-link img').attr('src'));
			
		$.get("_scripts/sendToFriend.php", 'action=gallery_get_hash&file=' + $('.advance-link img').attr('src'), onsharelinks);
		
	}
		
}

function showemail(hide) {
	if($('#email').css('visibility') == 'visible' || hide == true) $('#email').css('visibility', 'hidden');
	else {
		showshare(true);
		showtwitter(true);
		//showfacebook(true);
		$('#email').css('visibility', 'visible');
	}
}

function showtwitter(hide) {
	if($('#twitter').css('visibility') == 'visible' || hide == true) $('#twitter').css('visibility', 'hidden');
	else {
		showemail(true);
		//showfacebook(true);
		$('#twitter').css('visibility', 'visible');
	}
}

function showfacebook(hide) {
	if($('#facebook').css('visibility') == 'visible' || hide == true) $('#facebook').css('visibility', 'hidden');
	else {
		showemail(true);
		showtwitter(true);
		$('#facebook').css('visibility', 'visible');
	}
}

function sendtweet(event) {
	event.preventDefault();
	
	var thetweet = $('#thetweet').val();
	var followgaga = $('#ladygaga').attr('checked') == 'checked' ? 'true' : 'false';
	var followvmobile = $('#vmobile').attr('checked') == 'checked' ? 'true' : 'false';
	var dataString = 'ladygaga='+followgaga+'&vmobile='+followvmobile+'&tweet='+thetweet;
	
	//console.log(dataString);
	
	$.ajax({
		type: 'POST',
		url: '_scripts/tweet.php',
		data: dataString
	});
	
	return false;
}	



function onsharelinks(data) {
	
	var photopath = instore ? 'http://ladyvirgin.com/gallery-instore.php?id='+data : 'http://ladyvirgin.com/gallery.php?id='+data;
			
	//alert(data);
	$('#sharefacebook').attr('href', 'http://www.facebook.com/sharer.php?u='+photopath+'&t=VIRGIN%20MOBILE%20PRESENTS%20LADY%20GAGA%20MONSTER%20BALL%20TOUR');
	//$('#sharefacebook').bind('click', showfacebook).css('cursor', 'pointer');
	$('#img_src').attr('value', data);
	$('#sharetwitter').bind('click', showtwitter).css('cursor', 'pointer');
	$('#thetweet').attr('value', 'Check Out This Monster Photo '+photopath);
		
	$('#sharemyspace').attr('href', 'http://www.myspace.com/index.cfm?fuseaction=postto&' + 't=' + encodeURIComponent('LADY GAGA MONSTER PHOTO') + '&c=' + encodeURIComponent('View this Lady Gaga Monster Photo') + '&u=' + encodeURIComponent(photopath));
	
	
	$('#share').css('visibility', 'visible');
}


function month(m) {
	var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
	return months[m - 1];
}

function fixname(n) {
	return n.replace(/-/gi, ' ').substr(3);
}

function onImageChange() {
	
	var currImage = $('.advance-link img').attr('src');
	//alert(currImage);
	
	if(typeof(allLoveIt[currImage]) == "undefined") {
		allLoveIt[currImage] = new Array();
		allLoveIt[currImage]["loveItCount"] = 0;
		allLoveIt[currImage]["lastVote"] = 0;
	}
	
	$('#loveItCount').html(" : "+allLoveIt[currImage]["loveItCount"]);
	
	if(((serverTime - parseInt(allLoveIt[currImage]["lastVote"])) <= 86400) && (parseInt(allLoveIt[currImage]["lastVote"]) != 0)) {
		$('#loveit').addClass("disabled");
	} else {
		$('#loveit').removeClass("disabled");	
	}
	
	//alert(typeof(allLoveIt[currImage]["lastVote"]));
	
}