//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;
	}
}

function noBread()
{
    if ($("#breadcrumb").length == 0 && $("#intro").length == 0 && $("#promoArea").length == 0) {
        $("#containerInner").addClass("noBreadcrumb");
   }
}


//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() {
		
    function EnableDisableSubmitButton() {
        var submitButton = $('.search input[type=submit]');
        var searchField = $('.search input[type=text]');
        
        if (searchField.length > 0){
            var value = searchField.val();
            if (value != undefined && value.length < 1) {
				submitButton.attr('disabled', true);
			} else {
				submitButton.removeAttr('disabled');
			}
        }
    };

    EnableDisableSubmitButton();
    
    $('.search input[type=text]').keyup(EnableDisableSubmitButton);
		
	$(".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");
	});
}

//Language box overlay
function LanguageDropDown() {
		
	$(".language > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$(".language").toggleClass("openDropDown");
	});
	
	$(".language .dropDownContent").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent(".language").length==0) {
			$(".language").removeClass("openDropDown");
			$(".language .dropDownContent").hide();
		}
	});            
	
	$(".dropDownContent .close").click(function(e) {
		e.preventDefault();
		$(".language").removeClass("openDropDown");
		$(".dropDownContent").hide();		
	});	
}

//Language box overlay
function AcountSwitcher() {
		
	$(".profileSwitcherContainer > a").click(function(e) {
		e.preventDefault();
		$(this).next('div').toggle();
		$(".profileSwitcherContainer").toggleClass("openDropDown");
	});
	
	$(".profileSwitcherContainer .dropDownContent").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent(".profileSwitcherContainer").length==0) {
			$(".profileSwitcherContainer").removeClass("openDropDown");
			$(".profileSwitcherContainer .dropDownContent").hide();
		}
	});
}


//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 () {
	
	$('.imageFlowWrapper').each(function() {
		var galleryContent = $(this).children('.galleryContent');
		var galleryContainer = $(this).children('.imageflow');

		galleryContent.hide();
		galleryContainer.show();

		var imageCount = galleryContainer.children('img').size();
	var centerImage = Math.round(imageCount/2);
	
		var imageFlowInstance = new ImageFlow();

		imageFlowInstance.init({
			ImageFlowID: galleryContainer.attr('id'),
		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]
	});
	
		galleryContainer.children(".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');
		}
	);	
}

var AdvertTracking = {
	init: function() {

		if (!navigator.userAgent.match("iPhone") && !navigator.userAgent.match("iPod") && !navigator.userAgent.match("iPad")) {

			$("div.adFlash").each(function() {

				var container = $(this);
				container.empty();

				var rel = container.attr("rel");
				var rev = container.attr("rev");
				var dimensions = rev.split("x");

				var width = dimensions[0];
				var height = dimensions[1];

				container.flash({
					src: rel,
					width: dimensions[0],
					height: dimensions[1],
					wmode: 'transparent'
				});

				container.mouseup(function(e) {
					var link = $(this).siblings("input[type=hidden]").val();
					AdvertTracking.AddClick(link);
				});

			});

			$("div.htmlAd").click(function(e) {
				var link = $(this).find("input[type=hidden].trk").val();
				AdvertTracking.AddClick(link);
			});

		};

	},
	TrackIframeClick: function(advertID) {
		var iframe = $("#iframeAdvert" + advertID);
		if (iframe.length == 1) {
			var link = iframe.siblings("input[type=hidden]").val();
			AdvertTracking.AddClick(link);
		}
	},
	AddClick: function(uri) {
		$.get(uri + '&ajax=true', function(data) {
			// alert("saved click");
		});
	}
}

//Uploadify tool
var Uploadify = {
    initialize: function() {

        if ($('#AddImageMultiple').length > 0) {
            if ($('#AddImageContainer .error').length == 0 && !($('#AddImageMultiple').hasClass('defaultToSingle'))) {
                Uploadify.switchUploadForms();
            }

            this.addFormControls();

            var memberid = $("#uploadifyMemberID").val();
            var timestamp = $("#uploadifyTimestamp").val();
            var hash = $("#uploadifyHash").val();
            var uploadserverurl = $("#uploadServerUrl").val();

            var UploadifyFlashButton = $('#UploadifyFlashButton');
            UploadifyFlashButton.css("display", "inline");
            var flashOverlayWidth = UploadifyFlashButton.width() + 51;
            if (flashOverlayWidth == 51) {
                flashOverlayWidth = 100;
            }
            var flashOverlayHeight = UploadifyFlashButton.height();
            if (flashOverlayHeight == 0) {
                flashOverlayHeight = 26;
            }

            $('#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/general/blank.png', //'/_images/buttons/browse.png',
                'rollover': true,
                'width': flashOverlayWidth,
                'height': flashOverlayHeight,
                'wmode': 'transparent',
                'queueID': 'uploadQueue',
                'onCheckError': function() {
                    if ($('#ImageLimitReached')) {
                        $('#ImageLimitReached').fadeIn();
                    }
                },
                'onAllComplete': function(event, data) {
                    Uploadify.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) {
                        if (Uploadify.filesUploaded > 0) {
                            window.location = $("#uploadifyRedirectUrl").val();
                        }
                        else {
                            $('#uploadQueue .blankstate').show();
                        }
                    }
                }
            });

            if ($('#AddImageMultiple').hasClass('defaultToSingle')) {
                Uploadify.switchUploadForms();
            }

        }
    },
    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();
                    $('#uploadInProgress').removeClass('hidden');
                }
                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);
        ReplaceInnerTextWithTranslation('UseAdvancedUploader');

        //Add click event to 'use advanced uploader' link
        if ($('#UseAdvancedUploader')) {
            $('#UseAdvancedUploader').click(function(e) {
                e.preventDefault();
                Uploadify.switchUploadForms();
            });
        }
    }
}

//Get Translation
function ReplaceInnerTextWithTranslation(elementId) {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/Translations/Frontend/GetTranslationFromEnglish/?phrase=" + $('#' + elementId).text(),
        success: function(data) {
            if (data.TranslatedPhrase) {
                $('#' + elementId).text(data.TranslatedPhrase);
                return data.TranslatedPhrase;
            }
        }
    });
}

//Show Hide Profile Stats
function MiniProfileStats () {

	$('.profileStats li:not(.first)').hide();
	$('.profileStats ul').append('<a href="#" class="toggler open">Show More Stats</a>');

	$(".profileStats .toggler").toggle(
		function () {
			$('.profileStats li:not(.first)').fadeIn('slow');
			$(this).html('Show Less Stats');
			$(this).removeClass('open');
			$(this).addClass('close');
		},
		function () {
			$('.profileStats li:not(.first)').fadeOut('slow');
			$(this).html('Show More Stats');
			$(this).removeClass('close');
			$(this).addClass('open');
		}
	);
}

//Explore Toggler
function ExploreToggle() {

	var maxLiCount = 4;

	$('.exploreToggle .exploreItems li:gt(' + maxLiCount + ')').hide();

    $('.exploreToggle .exploreItems ul').append('<a href="#" class="toggler open">Show More Stats</a>');

    $(".exploreToggle .exploreItems ul .toggler").toggle(
		function () {
		$('.exploreToggle .exploreItems li:gt(' + maxLiCount + ')').fadeIn('slow');
		    $(this).html('Show Less Items');
		    $(this).removeClass('open');
		    $(this).addClass('close');
		},
		function () {
			$('.exploreToggle .exploreItems li:gt(' + maxLiCount + ')').fadeOut('slow');
		    $(this).html('Show More Items');
		    $(this).removeClass('close');
		    $(this).addClass('open');
		}
	);
}

//Show Hide Profile Stats
function MiniBasket () {

	$('.miniBasketContents').hide();
	$('.miniBasketSummary').append('<a href="#" class="toggler open">Show Mini Basket</a>');

	$(".miniBasketSummary .toggler").toggle(
		function () {
			$('.miniBasketContents').slideDown('slow');
			$(this).html('Show Mini Basket');
			$(this).removeClass('open');
			$(this).addClass('close');
		},
		function () {
			$('.miniBasketContents').slideUp('slow');
			$(this).html('Hide Mini Basket');
			$(this).removeClass('close');
			$(this).addClass('open');
		}
	);	
}


function MiniBasketRemoveButtons() {
    $(".miniBasketContents a.button.icon.delete").click(function(e) {

        e.preventDefault();

        $.ajax({
            url: $(this).attr("href") + "&ajax=true",
            type: "post",
            data: $(this).serialize(),
            dataType: "json",
            success: function(data) {
                $("#minibasketContainer").html(data.MiniBasketHtml);
                $('.miniBasketContents').show();
                MiniBasketRemoveButtons();
            }
        });
    });
}

//Show Hide Print Copy
function PrintPurchaseDetails () {

	$('.purchasePrint .intro').hide();
	$('.purchasePrint .hd').append('<a class="button gray printDetails" href="#">More Details</a>');

	$(".printDetails").toggle(
		function () {
			$('.purchasePrint .intro').slideDown('fast');
			$(this).html('Hide Details');
		},
		function () {
			$('.purchasePrint .intro').slideUp('fast');
			$(this).html('More Details');
		}
	);	
}

//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');
		}
	);	
}

//Random Image Split Button
function RandomSplitButton() {
		
	$(".randomToggle").click(function(e) {
		e.preventDefault();
		$(".randomToggle").parent().addClass("openDropDown");
	});
	
	$(".randomDropDown").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent(".randomToggle").length==0) {
			$(".randomToggle").parent().removeClass("openDropDown");
		}
	});            
		
}

function UpdatePostageOption(postageBandID) {
    var termsChecked = ($('#termsAndConditions:checked').length == 1 ? 'true' : 'false');

    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/ShopPurchase/Checkout/UpdatePostageAjax/?TermsChecked=" + termsChecked + "&PostageBandID=" + postageBandID,
        success: function(data) {
            if (data.PaymentSummaryHtml) {
                $('#checkoutPaymentSummary').replaceWith(data.PaymentSummaryHtml);
                Cufon.refresh();
                $('#checkoutPaymentSummary .singleCheck input').customInput();
            }
        }
    });
	
}

function TicketTabs() {

    if ($('.ticketType[tickettype=2]').length == 0) {
        $('#TicketFieldSet').prepend('<fieldset class="ticketType" tickettype="2" ><div class="ticketHd"><span>We\'re sorry there are no tickets currently available of this type.</span></div></fieldset>');
    }
    if ($('.ticketType[tickettype=1]').length == 0) {
        $('#TicketFieldSet').prepend('<fieldset class="ticketType" tickettype="1" ><div class="ticketHd"><span>We\'re sorry there are no tickets currently available of this type.</span></div></fieldset>');
    }  
    
	$('.ticketType[tickettype=2]').hide();
	$('.ticketType[tickettype=1]').show();
	$('#standardtickets').addClass('selected');
	$('#studenttickets').removeClass('selected');

    $('#standardtickets a').click(function (e) {
            $('.ticketType[tickettype=2]').hide();
            $('.ticketType[tickettype=1]').show();
            $('#standardtickets').addClass('selected');
            $('#studenttickets').removeClass('selected');
            return false;
        }
    );
    
    $('#studenttickets a').click(function (e) {
            $('.ticketType[tickettype=2]').show();
            $('.ticketType[tickettype=1]').hide();
            $('#studenttickets').addClass('selected');
            $('#standardtickets').removeClass('selected');
            return false;
        }
    );
    

}

$(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').size() > 0) {
		selectBoxWidth = '350px';
	} else if ($('.eventTickets select, #productDetails select').size() > 0) {
		selectBoxWidth = '60px';
	} else if ($('.gallerySelector .select select').size() > 0) {
		selectBoxWidth = '200px';
	} else if ($('.checkoutForm select').size() > 0) {
		selectBoxWidth = '300px';
	} else if ($('.ranking select').size() > 0) {
		selectBoxWidth = '100px';
	} 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: '200px', maxHeight: 200 });
	$('#search select').selectmenu({ style: 'dropdown', width: '110px', 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" }
	});*/

	$('#flashMap').empty();
	$('#flashMap').flash({
		src: '/_images/flash/WPO-Map.swf',
		width: 650,
		height: 320,
		allowFullScreen: true
	});

	/*$('#countdown').empty();
	$('#countdown').flash({
	src: '/_images/flash/wpo-countdown.swf',
	width: 293,
	height: 116,
	WMODE: 'transparent',
	flashvars: {
	START_DATE: '10/08/2011',
	START_TIME: '9:00',
	END_DATE: '25/08/2011',
	END_TIME: '5:30',
	Event_On_Text: "Event Now On!",
	Event_Finished_Text: "Event Finished!"
	}
	});*/

	/********************************************************************/
	/*					    	   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 favouritesWrapper = $(".wpoGalleriesCarousel .carousel").wrap("<div class='carouselContainer'>");

	if ($(".wpoGalleriesCarousel .carousel ul li").size() > 4) {
		favouritesWrapper.before("<a href='#' class='carouselControl prev'>Prev</a> <a href='#' class='carouselControl next'>Next</a>");
	}

	$(".wpoGalleriesCarousel .carousel").jCarouselLite({
		btnNext: ".wpoGalleriesCarousel .next",
		btnPrev: ".wpoGalleriesCarousel .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",
			disableWidth: 1,
			disableHeight: 1,
			titleText: getLightboxTitle(this),
			makeHover: false,
			descText: function() {
				return $(this).find("img").attr("alt");
			},
			onShow: function() {
				hideProductImageDesc();
			}
		});
	});

	function getLightboxTitle(link) {
		var img = $(link).find("img");
		return (img.attr("rel")) ? img.attr("rel") : '&nbsp;';
	}
	$(".ligthboxCaption").each(function() {
		$(this).ariaLightbox({
			pos: "auto",
			em: false,
			zIndex: "9999",
			disableWidth: 1,
			disableHeight: 1,
			titleText: getLightboxCaptionTitle(this),
			makeHover: false,
			descText: function() {
				return $(this).attr("rel");
			},
			onShow: function() {
				hideProductImageDesc();
			}
		});
	});

	function getLightboxCaptionTitle(link) {
		var capTitle = $(link);
		return (capTitle.attr("title")) ? capTitle.attr("title") : '&nbsp;';
	}

	//Product Image	
	function hideProductImageDesc() {
		if ($('#productImages').length > 0) {
			$('#ui-lightbox-description').hide();
		}
	}

	//Iframe
	function OpenIframeAriaPopup(link) {

		link = $(link);

		var frameWidth;
		var frameHeight;

		if (link.attr('rel')) {
			if (link.attr('rel') == 'View640Video') {
				frameWidth = 670;
				frameHeight = 530;
			}
			else {
				var dialogDimensions = link.attr('rel').split("x");
				frameWidth = dialogDimensions[0];
				frameHeight = dialogDimensions[1];
			}
		}
		else {
			frameWidth = 800;
			frameHeight = 500;
		}

		$('<div><iframe class="externalSite" width="' + (frameWidth - 20) + '" height="100%" frameborder="0" src="' + link.attr("href") + '" /></div>').dialog({
			title: (link.attr('title')) ? link.attr('title') : 'External Site',
			width: frameWidth + "px",
			height: frameHeight,
			close: function(event, ui) {
				$(".ui-widget-overlay").remove();
				link.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");
		});

	}

	$('.iframe').click(function(e) {
		e.preventDefault();
		OpenIframeAriaPopup(this);
	});

	function EnableJsLightboxLogin() {
		$("#headerLogin, #commentsLogin, #attendingEventsLogin, .loginPopUp").attr("href", "/login/?popup=true&Redirect=" + encodeURI(window.location.href));
		$("#headerLogin, #commentsLogin, #attendingEventsLogin, .loginPopUp").mousedown(function(e) {
			e.preventDefault();
			if (e.which == 1 || e.which == 2) {
				OpenIframeAriaPopup(this);
			}
		});
	}

	$("#navToDoOpener").click(function(e) {
		e.preventDefault();
		$(this).attr("title", $(this).attr("rev"));
		$(this).attr("href", "/todos/todos/listformember/?popup=true");
		OpenIframeAriaPopup(this);
	});

	// Random image pod

	function RandomPodLoaderHtml() {
		return '<div style="text-align: center; padding: 50px;"><img src="/_images/loader.gif" alt="loading" /></div>';
	}

	$('#refreshRandomImage').live('click', function(e) {
		e.preventDefault();
		$('#randomImageBd').html(RandomPodLoaderHtml());
		$.ajax({
			type: "GET",
			dataType: "json",
			url: "/images/pods/randomimagepod/?refresh_rnd_img_ajax=true",
			success: function(data) {
				if (data.Html) {
					$('#randomImage').replaceWith(data.Html);
					Cufon.refresh();
				}
			}
		});
	});

	// Random print pod

	$('#refreshRandomPrint').live('click', function(e) {
		e.preventDefault();
		$('#randomPrintBd').html(RandomPodLoaderHtml());
		$.ajax({
			type: "GET",
			dataType: "json",
			url: "/images/pods/randomprintpod/?refresh_rnd_img_ajax=true",
			success: function(data) {
				if (data.Html) {
					$('#randomPrint').replaceWith(data.Html);
					Cufon.refresh();
				}
			}
		});
	});

	//Random gallery pod

	$('#refreshRandomGallery').live('click', function(e) {
		e.preventDefault();
		$('#randomGalleryPodBd').html(RandomPodLoaderHtml());
		$.ajax({
			type: "GET",
			dataType: "json",
			url: "/images/pods/randomgalleriespod/?refresh_rnd_galleries_ajax=true",
			success: function(data) {
				if (data.Html) {
					$('#randomGalleryPod').replaceWith(data.Html);
					Cufon.refresh();
				}
			}
		});
	});

	// Competition Dialog

	$('.categoryDialogs').hide();

	$('.dialog').click(function(e) {
		e.preventDefault();

		var competitionDialog = "#" + $(this).attr('rel');

		$(competitionDialog).dialog({
			modal: true,
			autoOpen: false,
			width: 640,
			height: 260
		}).dialog('open');

	});

	//Product Options Accordian

	$('.ticketType .details').hide();

	$('.ticketHd h3 a').click(function() {
		$(this).parent().parent().next().slideToggle();
		$(this).parent().parent().toggleClass('open');
		return false;
	}).next().hide();


	// CarouFredSel

	$('#containerInner .promo .ft').show();
	$('#containerInner .promo .ft').append('<ul class="promoPaging"></ul>');

	var slideCounter = $('.promoSlider li').size();

	$(".promoSlider").carouFredSel({
		height: 225,
		width: 974,
		items: {
			visible: 1,
			width: 322,
			height: 225
		},
		scroll: {
			items: 1,
			pauseOnHover: true,
			onBefore: function(oldItems, newItems) {
				$(".promoPlay a").hide();
				$(".promoPause a").show();
			}
		},
		auto: 10000,
		prev: {
			button: ".promoPrevious",
			key: "left"
		},
		next: {
			button: ".promoNext",
			key: "right"
		},
		pagination: {
			container: ".promoPaging",
			anchorBuilder: function(nr) {
				var str = '<li><a href="#">';
				str += 'Slide' + ' ' + nr + ' ' + 'of' + ' ' + slideCounter;
				str += '</a></li>';
				return str;
			}
		}
	});

	$(".promoPlay a").click(function() {
		$(".promoSlider").trigger("play");
		$(this).hide();
		$('.promoPause a').show();
		return false;
	}).hide();

	$(".promoPause a").click(function() {
		$(".promoSlider").trigger("pause");
		$(this).hide();
		$('.promoPlay a').show();
		return false;
	});

	//Sectors
	$(".sampleImages li a").hover(function() {
		$(this).stop().animate({ top: -10 });
	}, function() {
		$(this).stop().animate({ top: 0 });
	});

	///
	EnableJsLightboxLogin();
	TicketTabs()
	PreventPasswordAutofill();
	ShowHide();
	DropDownMenu();
	LoginDropDown();
	SearchDropDown();
	ShareDropDown();
	GalleryWidget();
	SmoothScroll();
	DropDownUI();
	ImageSelection();
	AccountDropDown();
	Uploadify.initialize();
	GroupHeader();
	ShowHideRegion();
	errorScroll();
	//noBread();
	LanguageDropDown();
	RandomSplitButton();
	PrintPurchaseDetails();
	MiniProfileStats();
	MiniBasket();
	AcountSwitcher();
	ExploreToggle();
	MiniBasketRemoveButtons();
	AdvertTracking.init();

	// Uploadify integration for the high res image uploader

	var iHiResUploadify = 1;
	$(".hiResUploadify").each(function() {

		var basicUploader = $(".basicUploader", this);
		var advancedUploader = $(".advancedUploader", this);

		// Hide the basic upload section
		basicUploader.hide();
		advancedUploader.show();

		var uploadifyUrl = $("input[name=uploadifyUrl]", this).val();
		var uploadifyContainer = $(".advancedUploader .file", this);

		var uploadifyField = $("<input type='file' name='Uploadify' id='Uploadify" + iHiResUploadify + "' />");
		uploadifyContainer.append(uploadifyField);

		var queue = $(".uploadQueue", this);
		var queueId = "uploadQueue_" + iHiResUploadify;
		queue.attr("id", queueId);

		var alertBox = $(".uploadifyAlert", this);

		$("a", alertBox).click(function(e) {
			e.preventDefault();
			advancedUploader.show();
			alertBox.hide();
		});

		uploadifyField.uploadify({
			'uploader': '/_js/uploadify/uploadify.swf',
			'script': uploadifyUrl,
			'scriptAccess': 'always',
			'cancelImg': '/_js/uploadify/cancel.png',
			'auto': true,
			'multi': false,
			'fileDesc': 'Image Files',
			'fileExt': '*.jpg;*.jpeg;*.tiff;*.tif',
			'queueSizeLimit': 1,
			'wmode': 'transparent',
			'queueID': queueId,
			hideButton: true,
			onComplete: function(event, ID, fileObj, response, data) {

				alertBox.show()
				advancedUploader.hide();

				var filename = response;

				$(".filename", alertBox).html(filename);
				$("input[name=uploadedHiResFilePath]", basicUploader).val(filename);

			}
		});

		iHiResUploadify++;

	});

try
{
	FacebookConnect.Init();
}
catch(err)
{
}

});
	
$(window).load(function(){
	ImageSelection();
});
