//Scrolls page to an ID element if link has class of .scroll
function SmoothScroll() {
	$('.scroll').click(function() {
	  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
	  && location.hostname == this.hostname) {
		var $target = $(this.hash);
		$target = $target.length && $target
		|| $('[name=' + this.hash.slice(1) +']');
		if ($target.length) {
		  var targetOffset = $target.offset().top;
		  $('html,body')
		  .animate({scrollTop: targetOffset}, 1000);
		 return false;
		}
	  }
	});
}


//Scrolls page to first SXForm error
function errorScroll() {
	var errorTarget = $("div .error");
	
	if (errorTarget.length > 0){
		  var targetOffset = errorTarget[0].offsetTop;
		  $('html,body').animate({scrollTop: targetOffset}, 1000);
		 return false;
	}
}




//Loginbox overlay
function LoginDropDown() {
	
	$(".memberLogin > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$('input[id=username]').focus();
		$(".memberLogin").toggleClass("openDropDown");
	});
	
	$(".memberLogin .dropDownContent").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent(".memberLogin").length==0) {
			$(".memberLogin").removeClass("openDropDown");
			$(".memberLogin .dropDownContent").hide();
		}
	});
	
	$(".dropDownContent .close").click(function(e) {
		e.preventDefault();
		$(".memberLogin").removeClass("openDropDown");
		$(".dropDownContent").hide();		
	});
	
}

//Search box overlay
function SearchDropDown() {
		
	$(".search > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$('.search input[type=text]').focus();
		$(".search").toggleClass("openDropDown");
	});
	
	$(".search .dropDownContent").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent(".search").length==0) {
			$(".search").removeClass("openDropDown");
			$(".search .dropDownContent").hide();
		}
	});            
	
	$(".dropDownContent .close").click(function(e) {
		e.preventDefault();
		$(".memberLogin").removeClass("openDropDown");
		$(".dropDownContent").hide();		
	});	
}

//Share box overlay
function ShareDropDown() {
		
	$(".share > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$(".share").toggleClass("openDropDown");
	});
	
	$(".share .dropDownContent").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent(".share").length==0) {
			$(".share").removeClass("openDropDown");
			$(".share .dropDownContent").hide();
		}
	});            
	
	$(".dropDownContent .close").click(function(e) {
		e.preventDefault();
		$(".share").removeClass("openDropDown");
		$(".dropDownContent").hide();		
	});	
	
	$(".addthis_button_expanded").click(function() {
		$(".share .dropDownContent").hide();
		$(".share").removeClass("openDropDown");
	});
}

//Account box overlay
function AccountDropDown() {
		
	$(".account > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$(".account").toggleClass("openDropDown");
	});
	
	$(".account .dropDownContent").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent(".account").length==0) {
			$(".account").removeClass("openDropDown");
			$(".account .dropDownContent").hide();
		}
	});            
	
	$(".dropDownContent .close").click(function(e) {
		e.preventDefault();
		$(".account").removeClass("openDropDown");
		$(".dropDownContent").hide();		
	});	
	
}

//Generic drop down interface (not form selectbox)
function DropDownUI () {
	
	var dropdown = $(".dropDown");
	var toggler = $(".toggler");
		
	toggler.append('<span></span>').css("padding-right","35px");
	
	toggler.click(function(e) {
		e.preventDefault();	
		$(this).parent().toggleClass('active-dropdown');
	});

}

//Main nav drop down
function DropDownMenu () {
	
	var display_timeout = 0;
	$("li.has-subnav").hover(function () {
		$("li.has-subnav").removeClass('subnav-active');							   
		if(display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;
		$(this_element).addClass('subnav-active');
	},
	function () {
		if(display_timeout != 0) { clearTimeout(display_timeout); }
		var this_element = this;
		display_timeout = setTimeout(function() {
			display_timeout = 0;
			$(this_element).removeClass('subnav-active');
		}, 500); }
	);	
}

// Gallery Widget - Image Flow	
function GalleryWidget () {
	
	$('.galleryContent').hide();
	$('#galleryContainer').show();

	var imageCount = $("#galleryContainer img").size();
	var centerImage = Math.round(imageCount/2);
	
	var instanceOne = new ImageFlow();
	instanceOne.init({
		ImageFlowID:'galleryContainer',
		captions: false,
		reflections: false,
		startID: centerImage,
		circular: true,
		buttons: true, 
		//imagesM: 0.9,
		imageFocusMax: 3,
		//imageFocusM: 2,
		percentLandscape:145,
		aspectRatio: 3,
		xStep: 120,
		imageCursor: 'pointer',
		opacity: true,
		opacityArray: [10, 10, 8, 2]
	});
	
	$(".imageflow .previous, .imageflow .next").hover(function() {
		$(this).css("background-position", "0px -12px")
	}, function () {
		$(this).css("background-position", "0px 0px")
	});
}

//Show Hide
function ShowHide () {

	$('.collapseable .bd').hide();
	$('.collapseable .hd').append('<a href="#" class="button toggle">Show</a');

	$(".collapseable .toggle").toggle(
		function () {
			$(this).parent().next('div').slideDown();
			$(this).html('Hide');
		},
		function () {
			$(this).parent().next('div').slideUp();
			$(this).html('Show');
		}
	);	
}

//Image Selection
function ImageSelection () {
	
	// Remove selected button show/hide
	
	$('.selectedEntries li .remove, .imageGrid li .remove, .profiles li .remove').css({"right": "9999px"});
		
	$('.selectedEntries li .imageContainer, .imageGrid li .imageContainer, .profiles li .imageContainer').hover(function() {
		$(this).children('a.remove').css("right", "-12px");
	}, function() {
		$(this).children('a.remove').css("right", "9999px");
	});
	
	$('.selectedEntries li .remove, .imageGrid li .remove, .profiles li .remove').focusin(function() {
		$(this).css("right", "-12px");
	});
	
	$('.selectedEntries li .remove, .imageGrid li .remove, .profiles li .remove').focusout(function() {
		$(this).css("right", "9999px");
	});
	
	$('.imageGrid li .addOverlay, .selectedEntries .makePrimary').each(function() {
		var imgHeight = $(this).siblings('img').height() + 6;
		var imgWidth = $(this).siblings('img').width() + 6;
		$(this).css({"height": imgHeight, "width": imgWidth});
	});
}

//Show Hide Group Header
function GroupHeader () {

	$('#groupHeader .groupDescription').hide();
	$('#groupHeader').append('<a href="#" class="toggler open">Show Description</a>');

	$("#groupHeader .toggler").toggle(
		function () {
			$('#groupHeader .groupDescription').slideDown();
			$(this).html('Hide Description');
			$(this).removeClass('open');
			$(this).addClass('close');
		},
		function () {
			$('#groupHeader .groupDescription').slideUp();
			$(this).html('Show Description');
			$(this).removeClass('close');
			$(this).addClass('open');
		}
	);	
}

//Show Hide Select Region
function ShowHideRegion () {
	
	$('.mapSelect #flashMap').show();
	$('.selectRegion ul').hide();
	$('.selectRegion h2').before('<a href="#" class="button gray toggle open"><span>Show Regions</span></a>');

	$(".selectRegion .toggle").toggle(
		function () {
			$('.selectRegion ul').slideDown();
			$(this).html('<span>Hide Regions</span>');
			$(this).removeClass('open');
			$(this).addClass('close');
		},
		function () {
			$('.selectRegion ul').slideUp();
			$(this).html('<span>Show Regions</span>');
			$(this).removeClass('close');
			$(this).addClass('open');
		}
	);	
}

//Uploadify tool
var Uploadify = {
	initialize: function(){
		
		if ($('#AddImageMultiple'))
		{
			if ($('#AddImageContainer .error').length == 0)
			{
				Uploadify.switchUploadForms();
			}
			
			this.addFormControls();
			
			var memberid = $("#uploadifyMemberID").val();
			var timestamp = $("#uploadifyTimestamp").val();
			var hash = $("#uploadifyHash").val();
			var uploadserverurl = $("#uploadServerUrl").val();
			
			$('#Uploadify').uploadify({
				'uploader': '/_js/uploadify/uploadify.swf',
				'script': uploadserverurl,
				'scriptData': {'memberid' : memberid, 'timestamp' : timestamp, 'hash' : hash},
				'checkScript': '/images/images/uploadifyvalidateimagelimit/',
				'scriptAccess': 'always',
				'folder': '/uploads',
				'cancelImg': '/_js/uploadify/cancel.png',
				'auto': false,
				'multi': true,
				'fileDesc': 'Image Files',
				'fileExt': '*.jpg;*.jpeg;*.tiff;*.tif',
				'queueSizeLimit': 10,
				'sizeLimit': 5000000,
				'minSizeLimit': 800000,
				'buttonImg'	: '/_images/buttons/browse.png',
				'rollover'	: true,
				'width'		: 93,
				'height'	: 26,
				'wmode'		: 'transparent',
				'queueID'	: 'uploadQueue',
				'onCheckError': function()
					{
						if ($('#ImageLimitReached'))
						{
							$('#ImageLimitReached').fadeIn();
						}
					},
				'onAllComplete': function(event, data)
					{ 
						filesUploaded = data.filesUploaded
						
						if (data.errors == 0)
						{
							window.location = $("#uploadifyRedirectUrl").val(); 
						}
					},
				'onSelectOnce'	: function() { $('#uploadQueue .blankstate').hide(); },
				'onCancel'	: function(event, queueID, fileObj, data) 
					{
						var fileCount = data.fileCount;
						if (fileCount == 0 && filesUploaded > 0)
						{
							window.location = $("#uploadifyRedirectUrl").val(); 
						}
					}
			});
			
		}
	},
	filesUploaded: 0,
	switchUploadForms: function(){
		if ($('#AddImageContainer').hasClass('hidden'))
		{
			$('#AddImageContainer').removeClass('hidden');
			$('#AddImageMultipleContainer').addClass('hidden');
		}
		else
		{
			$('#AddImageContainer').addClass('hidden');
			$('#AddImageMultipleContainer').removeClass('hidden');
		}
	},
	addFormControls: function(){
	
		//Add Upload Field
		var formField = $('#UploadifyUploadField');
		var uploadField = $('<input type="file" name="Uploadify" id="Uploadify" />')
			
		formField.append(uploadField);
		
		//Add Start Upload Button
		if ($('#StartUpload'))
		{
			$('#StartUpload').click(function(e){
				e.preventDefault();
				
				if ($('#Uploadify').uploadifySettings('queueSize') > 0)
				{
					$('#Uploadify').uploadifyUpload();
				}
				else
				{
					$("#dialog-modal").dialog({
						height: 140,
						width: 400,
						modal: true
					});
				}
			});
		}
		
		//Add click event to 'use basic uploader' link
		if ($('#UseBasicUploader'))
		{
			$('#UseBasicUploader').click(function(e){
				e.preventDefault();
				Uploadify.switchUploadForms();
			});
		}
		
		//Add 'use advanced uploader' link
		var basicUploadForm = $('#AddImageContainer .hd');
		var switchToAdvancedFormLink = $('<a href="#" class="link" id="UseAdvancedUploader">Use advanced uploader</a>')
			
		basicUploadForm.append(switchToAdvancedFormLink);
		
		//Add click event to 'use advanced uploader' link
		if ($('#UseAdvancedUploader'))
		{
			$('#UseAdvancedUploader').click(function(e){
				e.preventDefault();
				Uploadify.switchUploadForms();
			});
		}	
	}
}

$(document).ready(function() {

    $('#introSlideshow').empty();

    //Tooltip for location map
    $(".pin").locationTip();

    //Ticker
    $('#ticker ul').innerfade({
        'containerheight': '26px',
        'timeout': 6000,
        'speed': 'slow'
    });

    $("a[rel*='external']").attr({ target: "_blank" });

    //Accessible, Custom checkboxs/radios
    $('.rememberMe input, .singleCheck input, .selectMultiple li input').customInput();

    //Custom selectboxes

    var selectBoxWidth;

    if ($('.galleryFilter .select select')) {
        selectBoxWidth = '250px';
    }
    else {
        selectBoxWidth = '160px';
    }

    $('.pod .select select').selectmenu({ style: 'dropdown', width: '290px', maxHeight: 200 });
    $('#contentCol .select select').selectmenu({ style: 'dropdown', width: selectBoxWidth, maxHeight: 200 });
    $('#contentCol .dateSelect select').selectmenu({ style: 'dropdown', width: '90px', maxHeight: 200 });
    $('.pod .dateSelect select').selectmenu({ style: 'dropdown', width: '85px', maxHeight: 200 });
    $('.profileSelector select').selectmenu({ style: 'dropdown', width: '250px', maxHeight: 200 });

    // Star Rating
    $('.starControl input').starRating();
    $('.writeCritique .starControl').addClass("enhancedStars");

    //Accordion
    $(".moduleList.faqs").accordion({ autoHeight: false });

    //Change border colour of focused input	
    $('.module input[type="text"], .module textarea, .module input[type="password"]').focus(function() {
        $(this).css("border-color", "#9b9b9b");
    });

    $('.module input[type="text"], .module textarea, .module input[type="password"]').blur(function() {
        $(this).css("border-color", "#dedede");
    });

    //Row Highlight
    $(".editSection tr, .selectList li").hover(function() { $(this).addClass('highlight'); }, function() { $(this).removeClass('highlight'); });

    //Password autocomplete off (validates - using autocomplete='off' doesn't until HTML5)
    function PreventPasswordAutofill() {
        $("input.disableAutoComplete").val('');
    }

    /********************************************************************/
    /*					    	   Flash								*/
    /********************************************************************/

    /*$('#videoPlayer').empty();
    $('#videoPlayer').flash({
    src: '/_images/flash/youtube-player.swf',
    width: 620,
    height: 395,
    allowFullScreen: true,
    flashvars: {youtubeID:"dGnAJ0vUxfc", width:"600", height:"355"}
    });*/

    /********************************************************************/
    /*					    	   Carousel								*/
    /********************************************************************/

    var galleriesWrapper = $(".galleriesCarousel .carousel").wrap("<div class='carouselContainer'>");

    if ($(".galleriesCarousel .carousel ul li").size() > 4) {
        galleriesWrapper.before("<a href='#' class='carouselControl prev'>Prev</a><a href='#' class='carouselControl next'>Next</a>");
    }

    $(".galleriesCarousel .carousel").jCarouselLite({
        btnNext: ".galleriesCarousel .next",
        btnPrev: ".galleriesCarousel .prev",
        visible: 4,
        speed: 400,
        circular: false
    });

    var favouritesWrapper = $(".favouritesCarousel .carousel").wrap("<div class='carouselContainer'>");

    if ($(".favouritesCarousel .carousel ul li").size() > 4) {
        favouritesWrapper.before("<a href='#' class='carouselControl prev'>Prev</a> <a href='#' class='carouselControl next'>Next</a>");
    }

    $(".favouritesCarousel .carousel").jCarouselLite({
        btnNext: ".favouritesCarousel .next",
        btnPrev: ".favouritesCarousel .prev",
        visible: 4,
        speed: 400,
        circular: false
    });

    var recentGroupsWrapper = $(".recentGroups .carousel").wrap("<div class='carouselContainer'>");

    if ($(".recentGroups .carousel ul li").size() > 4) {
        recentGroupsWrapper.before("<a href='#' class='carouselControl prev'>Prev</a> <a href='#' class='carouselControl next'>Next</a>");
    }

    $(".recentGroups .carousel").jCarouselLite({
        btnNext: ".recentGroups .next",
        btnPrev: ".recentGroups .prev",
        visible: 4,
        speed: 400,
        circular: false
    });

    var popularGroupsWrapper = $(".popularGroups .carousel").wrap("<div class='carouselContainer'>");

    if ($(".popularGroups .carousel ul li").size() > 4) {
        popularGroupsWrapper.before("<a href='#' class='carouselControl prev'>Prev</a> <a href='#' class='carouselControl next'>Next</a>");
    }

    $(".popularGroups .carousel").jCarouselLite({
        btnNext: ".popularGroups .next",
        btnPrev: ".popularGroups .prev",
        visible: 4,
        speed: 400,
        circular: false
    });

    $('.carouselControl').click(function(e) { e.preventDefault(); });

    /********************************************************************/
    /*      	   Location Tabs - Delete when Dev'ed					*/
    /********************************************************************/

    $('#festivalsMap .tabs').show();

    $('.wpoEvents').click(function(e) {
        e.preventDefault();
        if ($('#wpoEvents').is(":hidden")) {
            $('#festivalsMap .tabs li').removeClass('selected');
            $(this).parent().addClass('selected');
            $('#festivalsMap .bd div').fadeOut();
            $('#wpoEvents').delay(350).fadeIn();
        }
    });

    $('.otherPhotoEvents').click(function(e) {
        e.preventDefault();
        if ($('#otherEvents').is(":hidden")) {
            $('#festivalsMap .tabs li').removeClass('selected');
            $(this).parent().addClass('selected');
            $('#festivalsMap .bd div').fadeOut();
            $('#otherEvents').delay(350).fadeIn();
        }
    });
    /********************************************************************/
    /*					    	   Dialogs								*/
    /********************************************************************/

    //Upload New Image

    //$('#uploadButton').click(function(e) { e.preventDefault(); $("#uploadImage").dialog('open') });

    /*$("#uploadImage").dialog({
    modal: true,
    draggable: false,
    width: 400,
    autoOpen: false,
    zIndex: 3001
    });*/

    $(".lightbox").each(function() {
        $(this).ariaLightbox({
            pos: "auto",
            em: false,
            zIndex: "9999",
            titleText: getLightboxTitle(this),
            makeHover: false,
            descText: function() {
                return $(this).find("img").attr("alt");
            }
        });
    });

    function getLightboxTitle(link) {
        var img = $(link).find("img");
        return (img.attr("rel")) ? img.attr("rel") : '&nbsp;';
    }

    $('.iframe').click(function(e) {
        e.preventDefault();
        var $this = $(this);

        $('<div><iframe class="externalSite" width="780" height="100%" frameborder="0" src="' + this.href + '" /></div>').dialog({
            title: ($this.attr('title')) ? $this.attr('title') : 'External Site',
            width: 800,
            height: 500,
            close: function(event, ui) {
                $(".ui-widget-overlay").remove();
                $(this).dialog("destroy");
                $(".externalSite").remove();
            }
        });

        $(".ui-dialog").before("<div class='ui-widget-overlay'></div>");
        $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px").css("z-index", "1001");

        $(window).resize(function() {
            $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px");
        });

    });

    PreventPasswordAutofill();
    ShowHide();
    DropDownMenu();
    LoginDropDown();
    SearchDropDown();
    ShareDropDown();
    GalleryWidget();
    SmoothScroll();
    DropDownUI();
    ImageSelection();
    AccountDropDown();
    Uploadify.initialize();
    GroupHeader();
    ShowHideRegion();
    errorScroll();
});

$(window).load(function(){
	ImageSelection();
});