$(function() {
	
	var EALBUM = {};	
	
	EALBUM.datepicker = (function () {
		
		var datepicker = $('#datepicker'),
		
			buttons,
		
			wheels,			
			numWheels,						
			wheelItemHeight,
			wheelItemTemplate,			
			startScroll,			
			scrolling,
			direction,
			
			dobSelects,			
			dobDefaults,			
			startButton,			
			form,
			
			replaceFonts = function () {
				
				// seems to be an issue with asynchonrously loading cufon in ie so I'm not loading it

				if(!$.browser.msie) {
					
					$.getScript('/templates/default/js/cufon-and-font.js', function () {
					
						var opts = {
							textShadow: '1px 1px black'
						};
						
						Cufon.set('fontFamily', 'SansaSoft-Bold').replace('#pickers li', opts);
						Cufon.set('fontFamily', 'Sansa-Normal').replace('h3,#datepicker_message', opts);
						Cufon.now();
						
					});
					
				} else {
					wheels.css('lineHeight','45px');
				}
				
			},
			
			pad = function (number, length) {
				
				var str = '' + number;
				
				while(str.length < length) {
					str = '0' + str;
				}
				
				return str;
				
			},
			
			genArray = function (limit,start) {
				
				var data = [],
					i;
									
				for(i = start; i <= limit; i+=1) {
					data.push(pad(i,2));
				}
				
				return data;
				
			},
						
			getData = function (type) {
				
				switch (type) {
					
				case 'days':
					return genArray(31,1);
					break;
					
				case 'months':
					return genArray(12,1);
					break;
					
				case 'years':
				
					var thisYear = (new Date).getFullYear(),
						firstYear = 1939;		
	
					return genArray(thisYear, firstYear).reverse();
					
					break;
					
				}

			},
			
			data = {
				days: getData('days'),
				months: getData('months'),
				years: getData('years')
			},
						
			injectData = function (target,index) {
				
				var type = target.attr('id').split('_')[0],
					typeData = data[type],
					numRows = typeData.length,
					html = '<ul>',
					i;
				
				for(i = 0; i < numRows; i+=1) {
					
					html += wheelItemTemplate.replace('{{number}}',typeData[i]);
					
				}
				
				html += '</ul>';
				
				target.html(html);
				
				
			},
			
			buildWheels = function () {
				
				var	i;	
					
				for(i = 0; i < numWheels; i+=1) {
					
					var el = $(wheels[i]);
					
					injectData(el,i);
								
				}
				
			},
			
			setSelected = function () {
				
				var el = wheels.eq(scrolling).children('ul'),
					top = stripPixels(el.css('top')).toFixed(0) - wheelItemHeight,
					itemPos = -(top / wheelItemHeight);
					
				dobSelects.eq(scrolling).val(parseInt(($.trim(el.find('li').eq(itemPos).text())),10));			
				
			},
						
			stripPixels = function (value) {
				
				return parseInt(value.replace('px',''),10);
				
			},

			scroll = function () {

				var el = wheels.eq(scrolling).children('ul'),
					distance = wheelItemHeight,
					top = stripPixels(el.css('top')),
					lowerLimit = wheelItemHeight,
					upperLimit = -((wheels.eq(scrolling).find('li').length - 2) * wheelItemHeight),
					operator;
						
				if(direction === 'up') {
					operator = '-=';
				} else {
					operator = '+=';
				}								
				
				if(top === lowerLimit && direction === 'down' || top === upperLimit && direction === 'up') {
					return false;
				}
				
				el.animate({
					top: operator + distance
				},100, function () {
					setSelected();
				});
		
			},	
			
			buttonLogic = function () {				
			
				var el = $(this);
					
				direction = el.data('direction');
					
				scrolling = el.data('index');
				
				scroll();
				
			},
			
			bindEvents = function () {
				
				startButton.click(start);
				
				buttons.mousehold(buttonLogic);
				
			},
			
			start = function () {
				
				form.submit();
				
			},
		
			setDobValues = function () {
				
				$.each(dobSelects, function (i,el) {					
					$(el).val(dobDefaults[i]);						
				});
				
			},
		
			init = (function () {
								
				if(datepicker.length) {
														
					wheels = $('.wheel');
					
					buttons = $('#top_button_row span,#bottom_button_row span');
					
					replaceFonts();
					
					numWheels = wheels.length;		
					wheelItemHeight = 55;
					wheelItemTemplate = '<li>{{number}}</li>';
										
					form = $('#albumForm');
					dobSelects = form.find('select');
					dobDefaults = ['1','1','2011'];
					
					startButton = $('#datepicker_button span');					
					
					setDobValues();
					
					buildWheels();					
					bindEvents();
					
				}
				
			})();
		
	})();
	
	function rand ( n )
	{
  		return ( Math.floor ( Math.random ( ) * n + 1 ) );
	}

	randomNumber = rand(9);
	
	var $ss = $('#slideshow');          
	// add slides to slideshow (images 2-8) 
	for (var i = 1; i < 14; i++) 
 		$ss.append('<a href="/"><img src="/templates/default/images/logos_new/'+i+''+randomNumber+'.jpg" width="125" height="152" /></a>');  
// start the slideshow 
	$ss.cycle({
		timeout: 15000  // milliseconds between slide transitions
	});
	
	if($('div.gd_heading').length > 0) {
		$('div.gd_heading img').ifixpng();
	}
							
	// change track list & play next cd
	if($('div#tracks').length > 0) {		
		
		// function to change album view
		function changeAlbum() {
			$('div#tracks div:visible').fadeOut(250, function() {
				$('div#album'+albumNumber).fadeIn(250);	
			});
		};
		// define the view buttons as the even images within cd controls
		viewButton = $('div.cdControls img:even');
		// hide all the playlists bar the first one
		$('div#tracks div:not(:first)').hide();	
		// attach a click listener to the view buttons
		viewButton.click(function(e) {
			// get the click event targets alt tag and store it in a var
			alt = $(e.target).attr('alt')
			// get the album number by getting the value of the last character of the alt var
			albumNumber = alt.charAt(alt.length-1);
			// change the album view
			changeAlbum();
			// prevent default behaviour
			return false;
		});
		// define the play buttons as the odd images within cd controls 
		playButton = $('div.cdControls img:odd');
		// attach a click listener to the play buttons
		playButton.click(function(e) {
			// define the player var
			var mp3 = document.getElementById("player");
			// get the click event targets alt tag and store it in a var
			alt = $(e.target).attr('alt')
			// get the album number by getting the value of the last character of the alt var
			albumNumber = alt.charAt(alt.length-1);
			// if clicking play album 1
			if(albumNumber == 1) {
				// define trackNumber var as 0 or the first track
				trackNumber = 0;
				// change the album view
				changeAlbum();
			}
			// if clicking play album 2
			else if(albumNumber == 2) {
				// define trackNumber var as 20
				trackNumber = 20;
				// change the album view
				changeAlbum();
			}
			// if clicking play album 3
			else if(albumNumber == 3) {
				// define trackNumber var as 40
				trackNumber = 40;
				// change the album view
				changeAlbum();
			}
			else if(albumNumber == 4) {
				// define trackNumber var as 40
				trackNumber = 60;
				// change the album view
				changeAlbum();
			}
			// send the player an ITEM event with the trackNumber var as its parameter
			mp3.sendEvent("ITEM",trackNumber);	
			// prevent default behaviour
			return false;
		});		
	}	
	
	//selects
	if($('input[type=text],input[type=password]').length > 0) {	
		$('.right li select').after('<span class="capRight"></span>').wrap('<span class="capLeft"></span>');
		$('input[type=text],[type=select],[type=password],[type=file],input[type=password]').after('<span class="capRight"></span>').wrap('<span class="capLeft"></span>');	
	}
	
	$('img#customart').parent('a').click(function() {
		return false;											  
	});
	
	if($('#albumForm').length > 0) {
	
		var albumForm = '#albumForm',
			born_day = $(albumForm + ' select[name="day"]').val(),
			born_month = $(albumForm + ' select[name="month"]').val(),
			born_year = $(albumForm + ' select[name="year"]').val(),
			now = new Date();
		
		function bornDate() {
			born_date = born_month+'/'+born_day+'/'+born_year;
			born = new Date(born_date);
			years = Math.floor((now.getTime() - born.getTime()) / (365 * 24 * 60 * 60 * 1000));
			if(isNaN(years)) { 
				return false;
			} else {
 				$(albumForm + ' input[name="ageCalc"]').val(years+' years');
 			}
		}
		
		bornDate();
		
		$(albumForm + ' select[name="day"]').change(function(e) {
			born_day = $(e.target).val();	
			bornDate();		
		});
		
		$(albumForm + ' select[name="month"]').change(function(e) {
			born_month = $(e.target).val();	
			bornDate();
		});	
		
		$(albumForm + ' select[name="year"]').change(function(e) {
			born_year = $(e.target).val();
			bornDate();
		});	
		
	}
	
	if($('div.cdControls').length > 0) {
		
		// populate the listen/preview message			
		
		var inputs = $('input[name^="line"]'),
			colour = $('input[name="custom_color"]').val();	
		
		$('div#album').append('<div id="message_container" class="review_message"></div>');
		
		for(var x = 0; x < inputs.length; x++) {
	
			if($(inputs[x]).val() != '') {
				
				var lineNumber = x + 1,
					lineMessage = $(inputs[x]).val(),
					character = '',
					images = '';
				
				$('div#message_container').append('<div id="line' + lineNumber +'" />');
				
				$('div#line' + lineNumber).css('height','30px').html('<img src="/templates/default/images/fonts/'+colour+'/left_cap_'+colour+'.png" alt="left cap" /><div id="line'+lineNumber+'message"></div><img src="/templates/default/images/fonts/'+colour+'/right_cap_'+colour+'.png" alt="right cap" />');
				
				for(var i = 0; i < lineMessage.length; i++) {
					character = lineMessage.charCodeAt(i);					
					images += '<img src="/templates/default/images/fonts/'+colour+'/'+character+'_'+colour+'.jpg">';	
				}		
				
				document.getElementById('line'+lineNumber+'message').innerHTML = images;
				
			}
		
		}
							
	}
	
	
	if($('button.disabled').length > 0) {
		$('input#tnccheckbox').click(function() {
			if($('input#tnccheckbox:checked').val() == "on") {
				$('button.disabled').removeAttr("disabled").css("cursor","pointer").children("img").attr("src","/templates/default/images/click_button.jpg");
			}
			if($('input#tnccheckbox:checked').val() == undefined) {
				$('button.disabled').attr("disabled","disabled").css("cursor","default").children("img").attr("src","/templates/default/images/click_button_disabled.jpg");	 
			}
		});
	}
	
	$('html').removeClass('fouc');
	
		
	$('p.toTop a').click(function(){
		$.scrollTo( 0, 500);
		return false;
	});
	/*
if(("input[name='artworkId']:checked").val()!==null) {

}
if(("input[id='customart']:checked").val()!==null) {
$("#preview").attr("src","/images/artwork/alb_"+$("input[name='artworkId']:checked").attr('id'));
}
*/
	if($("input[name='artworkId']:checked").length >0) {
		$("#preview_artwork").attr("src","/images/artwork/alb_"+$("input[name='artworkId']:checked").attr('id'));
	}
	
	if ( ! $("input[alt='custom']").is(':checked') )
	{	
		$("#use_custom").attr("value","0");	
		
	}

	$("input[name='artworkId']").click( function() {										   
		var imname=($("input[name='artworkId']:checked").attr('id') );							   
		$('#custom_fields').slideDown(0);
		
		$('div.review_cat img').ifixpng();
		$('#uploader').hide(200);
		$("#preview_artwork").attr("src","/images/artwork/alb_"+imname);
		
		
		if ( ! $("input[alt='custom']").is(':checked') )
	{	
		$("#use_custom").attr("value","0");	
	
	}
		
		
	});
	
	$("input[alt='custom']").click( function() {	
		$('#uploader').slideDown(200);
		$("#use_custom").attr("value","1");
	}); 
	
	$('#upload_button').click( function() {
	$('#uploadLi').slideUp(100);
	
	$('#uploadProgress').slideDown(0);	
		return ajaxFileUpload();
	});
   
   	$('a#showtnc').click(function() {
		$('div#tncregister').toggle();
		return false;
	});
   	$('#closeLabel').click(function() {
		$('div#tncregister').toggle();
		return false;
	});	
	
	if($('li.useDate a').length > 0) {
	
		$('li.useDate a').click(function() {
										 
			var occasionDateArray = $('select:lt(3) option:selected'),
				todaysDate = new Date(),
				thisYear = todaysDate.getFullYear(),
				thisMonth = todaysDate.getMonth(),
				thisDate = todaysDate.getDate()
				todaysDate = new Date(thisYear,thisMonth,thisDate).getTime();
				
				// adjust for jan being 0 not 1
				monthOffset = 1,
				occasionDate = new Date(thisYear,$(occasionDateArray[1]).val() - monthOffset,$(occasionDateArray[0]).val()).getTime(),
				sendDate = $('li.useDate select');	
			
			for(var x = 0; x < occasionDateArray.length - 1; x++) {	
				$(sendDate[x]).val($(occasionDateArray[x]).val());
			}
			
			if((todaysDate - occasionDate) > 0) {
				// add one to the year
				$(sendDate[2]).val(thisYear + 1);
			}
			else {
				$(sendDate[2]).val(thisYear);
			}
			
			return false;
			
		});
	
	}
	
	if($('a[rel=playlists]').length) {
	
		$('a[rel=playlists]').colorbox({								   
			transition:'elastic',
			speed:500,
			width: "500px",
			height: "90%",
			iframe: true
		});
		
	}
	
	if($('a[rel=shadowbox]').length) {
		
		$('a[rel=shadowbox]').colorbox({
			transition:'elastic',
			speed:500
		});
		
	}
	
	if($('#terms_and_conditions').length) {
		
		$('#terms_and_conditions').colorbox({
			transition:'elastic',
			speed:500,
			iframe: true,
			width: 800,
			height: 800,
			maxHeight: '95%'
		});
		
	}
	
	$('a[rel=shadowbox],a[rel=playlists]').click(function() {
		$("html").css("overflow-y","hidden");								 
	});
	
	$(document).bind('cbox_closed', function(){
    	$("html").css({"overflow-y": "scroll","overflow-x": "hidden"});
		$('#cboxNext,#cboxPrevious').css("background","none");
	});
   
});

window.log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments))}};

/*
 * jQuery Cycle Plugin (core logic only)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2009 M. Alsup
 * Version: 2.63 (17-MAR-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.2.6 or later
 *
 * Originally based on the work of:
 *	1) Matt Oakes
 *	2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/)
 *	3) Benjamin Sterling (http://www.benjaminsterling.com/experiments/jqShuffle/)
 */
;(function($){var ver="2.63";if($.support==undefined){$.support={opacity:!($.browser.msie)};}function log(){if(window.console&&window.console.log){window.console.log("[cycle] "+Array.prototype.join.call(arguments," "));}}$.fn.cycle=function(options,arg2){var o={s:this.selector,c:this.context};if(this.length==0&&options!="stop"){if(!$.isReady&&o.s){log("DOM not ready, queuing slideshow");$(function(){$(o.s,o.c).cycle(options,arg2);});return this;}log("terminating; zero elements found by selector"+($.isReady?"":" (DOM not ready)"));return this;}return this.each(function(){options=handleArguments(this,options,arg2);if(options===false){return;}if(this.cycleTimeout){clearTimeout(this.cycleTimeout);}this.cycleTimeout=this.cyclePause=0;var $cont=$(this);var $slides=options.slideExpr?$(options.slideExpr,this):$cont.children();var els=$slides.get();if(els.length<2){log("terminating; too few slides: "+els.length);return;}var opts=buildOptions($cont,$slides,els,options,o);if(opts===false){return;}if(opts.timeout||opts.continuous){this.cycleTimeout=setTimeout(function(){go(els,opts,0,!opts.rev);},opts.continuous?10:opts.timeout+(opts.delay||0));}});};function handleArguments(cont,options,arg2){if(cont.cycleStop==undefined){cont.cycleStop=0;}if(options===undefined||options===null){options={};}if(options.constructor==String){switch(options){case"stop":cont.cycleStop++;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);}cont.cycleTimeout=0;$(cont).removeData("cycle.opts");return false;case"pause":cont.cyclePause=1;return false;case"resume":cont.cyclePause=0;if(arg2===true){options=$(cont).data("cycle.opts");if(!options){log("options not found, can not resume");return false;}if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}go(options.elements,options,1,1);}return false;default:options={fx:options};}}else{if(options.constructor==Number){var num=options;options=$(cont).data("cycle.opts");if(!options){log("options not found, can not advance slide");return false;}if(num<0||num>=options.elements.length){log("invalid slide index: "+num);return false;}options.nextSlide=num;if(cont.cycleTimeout){clearTimeout(this.cycleTimeout);cont.cycleTimeout=0;}if(typeof arg2=="string"){options.oneTimeFx=arg2;}go(options.elements,options,1,num>=options.currSlide);return false;}}return options;}function removeFilter(el,opts){if(!$.support.opacity&&opts.cleartype&&el.style.filter){try{el.style.removeAttribute("filter");}catch(smother){}}}function buildOptions($cont,$slides,els,options,o){var opts=$.extend({},$.fn.cycle.defaults,options||{},$.metadata?$cont.metadata():$.meta?$cont.data():{});if(opts.autostop){opts.countdown=opts.autostopCount||els.length;}var cont=$cont[0];$cont.data("cycle.opts",opts);opts.$cont=$cont;opts.stopCount=cont.cycleStop;opts.elements=els;opts.before=opts.before?[opts.before]:[];opts.after=opts.after?[opts.after]:[];opts.after.unshift(function(){opts.busy=0;});if(!$.support.opacity&&opts.cleartype){opts.after.push(function(){removeFilter(this,opts);});}if(opts.continuous){opts.after.push(function(){go(els,opts,0,!opts.rev);});}saveOriginalOpts(opts);if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($slides);}if($cont.css("position")=="static"){$cont.css("position","relative");}if(opts.width){$cont.width(opts.width);}if(opts.height&&opts.height!="auto"){$cont.height(opts.height);}if(opts.startingSlide){opts.startingSlide=parseInt(opts.startingSlide);}if(opts.random){opts.randomMap=[];for(var i=0;i<els.length;i++){opts.randomMap.push(i);}opts.randomMap.sort(function(a,b){return Math.random()-0.5;});opts.randomIndex=0;opts.startingSlide=opts.randomMap[0];}else{if(opts.startingSlide>=els.length){opts.startingSlide=0;}}opts.currSlide=opts.startingSlide=opts.startingSlide||0;var first=opts.startingSlide;$slides.css({position:"absolute",top:0,left:0}).hide().each(function(i){var z=first?i>=first?els.length-(i-first):first-i:els.length-i;$(this).css("z-index",z);});$(els[first]).css("opacity",1).show();removeFilter(els[first],opts);if(opts.fit&&opts.width){$slides.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}var reshape=opts.containerResize&&!$cont.innerHeight();if(reshape){var maxw=0,maxh=0;for(var i=0;i<els.length;i++){var $e=$(els[i]),e=$e[0],w=$e.outerWidth(),h=$e.outerHeight();if(!w){w=e.offsetWidth;}if(!h){h=e.offsetHeight;}maxw=w>maxw?w:maxw;maxh=h>maxh?h:maxh;}if(maxw>0&&maxh>0){$cont.css({width:maxw+"px",height:maxh+"px"});}}if(opts.pause){$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});}if(supportMultiTransitions(opts)===false){return false;}if(!opts.multiFx){var init=$.fn.cycle.transitions[opts.fx];if($.isFunction(init)){init($cont,$slides,opts);}else{if(opts.fx!="custom"&&!opts.multiFx){log("unknown transition: "+opts.fx,"; slideshow terminating");return false;}}}var requeue=false;options.requeueAttempts=options.requeueAttempts||0;$slides.each(function(){var $el=$(this);this.cycleH=(opts.fit&&opts.height)?opts.height:$el.height();this.cycleW=(opts.fit&&opts.width)?opts.width:$el.width();if($el.is("img")){var loadingIE=($.browser.msie&&this.cycleW==28&&this.cycleH==30&&!this.complete);var loadingOp=($.browser.opera&&this.cycleW==42&&this.cycleH==19&&!this.complete);var loadingOther=(this.cycleH==0&&this.cycleW==0&&!this.complete);if(loadingIE||loadingOp||loadingOther){if(o.s&&opts.requeueOnImageNotLoaded&&++options.requeueAttempts<100){log(options.requeueAttempts," - img slide not loaded, requeuing slideshow: ",this.src,this.cycleW,this.cycleH);setTimeout(function(){$(o.s,o.c).cycle(options);},opts.requeueTimeout);requeue=true;return false;}else{log("could not determine size of image: "+this.src,this.cycleW,this.cycleH);}}}return true;});if(requeue){return false;}opts.cssBefore=opts.cssBefore||{};opts.animIn=opts.animIn||{};opts.animOut=opts.animOut||{};$slides.not(":eq("+first+")").css(opts.cssBefore);if(opts.cssFirst){$($slides[first]).css(opts.cssFirst);}if(opts.timeout){opts.timeout=parseInt(opts.timeout);if(opts.speed.constructor==String){opts.speed=$.fx.speeds[opts.speed]||parseInt(opts.speed);}if(!opts.sync){opts.speed=opts.speed/2;}while((opts.timeout-opts.speed)<250){opts.timeout+=opts.speed;}}if(opts.easing){opts.easeIn=opts.easeOut=opts.easing;}if(!opts.speedIn){opts.speedIn=opts.speed;}if(!opts.speedOut){opts.speedOut=opts.speed;}opts.slideCount=els.length;opts.currSlide=opts.lastSlide=first;if(opts.random){opts.nextSlide=opts.currSlide;if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{opts.nextSlide=opts.startingSlide>=(els.length-1)?0:opts.startingSlide+1;}var e0=$slides[first];if(opts.before.length){opts.before[0].apply(e0,[e0,e0,opts,true]);}if(opts.after.length>1){opts.after[1].apply(e0,[e0,e0,opts,true]);}if(opts.next){$(opts.next).click(function(){return advance(opts,opts.rev?-1:1);});}if(opts.prev){$(opts.prev).click(function(){return advance(opts,opts.rev?1:-1);});}if(opts.pager){buildPager(els,opts);}exposeAddSlide(opts,els);return opts;}function saveOriginalOpts(opts){opts.original={before:[],after:[]};opts.original.cssBefore=$.extend({},opts.cssBefore);opts.original.cssAfter=$.extend({},opts.cssAfter);opts.original.animIn=$.extend({},opts.animIn);opts.original.animOut=$.extend({},opts.animOut);$.each(opts.before,function(){opts.original.before.push(this);});$.each(opts.after,function(){opts.original.after.push(this);});}function supportMultiTransitions(opts){var txs=$.fn.cycle.transitions;if(opts.fx.indexOf(",")>0){opts.multiFx=true;opts.fxs=opts.fx.replace(/\s*/g,"").split(",");for(var i=0;i<opts.fxs.length;i++){var fx=opts.fxs[i];var tx=txs[fx];if(!tx||!txs.hasOwnProperty(fx)||!$.isFunction(tx)){log("discarding unknown transition: ",fx);opts.fxs.splice(i,1);i--;}}if(!opts.fxs.length){log("No valid transitions named; slideshow terminating.");return false;}}else{if(opts.fx=="all"){opts.multiFx=true;opts.fxs=[];for(p in txs){var tx=txs[p];if(txs.hasOwnProperty(p)&&$.isFunction(tx)){opts.fxs.push(p);}}}}if(opts.multiFx&&opts.randomizeEffects){var r1=Math.floor(Math.random()*20)+30;for(var i=0;i<r1;i++){var r2=Math.floor(Math.random()*opts.fxs.length);opts.fxs.push(opts.fxs.splice(r2,1)[0]);}log("randomized fx sequence: ",opts.fxs);}return true;}function exposeAddSlide(opts,els){opts.addSlide=function(newSlide,prepend){var $s=$(newSlide),s=$s[0];if(!opts.autostopCount){opts.countdown++;}els[prepend?"unshift":"push"](s);if(opts.els){opts.els[prepend?"unshift":"push"](s);}opts.slideCount=els.length;$s.css("position","absolute");$s[prepend?"prependTo":"appendTo"](opts.$cont);if(prepend){opts.currSlide++;opts.nextSlide++;}if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($s);}if(opts.fit&&opts.width){$s.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}s.cycleH=(opts.fit&&opts.height)?opts.height:$s.height();s.cycleW=(opts.fit&&opts.width)?opts.width:$s.width();$s.css(opts.cssBefore);if(opts.pager){$.fn.cycle.createPagerAnchor(els.length-1,s,$(opts.pager),els,opts);}if($.isFunction(opts.onAddSlide)){opts.onAddSlide($s);}else{$s.hide();}};}$.fn.cycle.resetState=function(opts,fx){fx=fx||opts.fx;opts.before=[];opts.after=[];opts.cssBefore=$.extend({},opts.original.cssBefore);opts.cssAfter=$.extend({},opts.original.cssAfter);opts.animIn=$.extend({},opts.original.animIn);opts.animOut=$.extend({},opts.original.animOut);opts.fxFn=null;$.each(opts.original.before,function(){opts.before.push(this);});$.each(opts.original.after,function(){opts.after.push(this);});var init=$.fn.cycle.transitions[fx];if($.isFunction(init)){init(opts.$cont,$(opts.elements),opts);}};function go(els,opts,manual,fwd){if(manual&&opts.busy&&opts.manualTrump){$(els).stop(true,true);opts.busy=false;}if(opts.busy){return;}var p=opts.$cont[0],curr=els[opts.currSlide],next=els[opts.nextSlide];if(p.cycleStop!=opts.stopCount||p.cycleTimeout===0&&!manual){return;}if(!manual&&!p.cyclePause&&((opts.autostop&&(--opts.countdown<=0))||(opts.nowrap&&!opts.random&&opts.nextSlide<opts.currSlide))){if(opts.end){opts.end(opts);}return;}if(manual||!p.cyclePause){var fx=opts.fx;curr.cycleH=curr.cycleH||$(curr).height();curr.cycleW=curr.cycleW||$(curr).width();next.cycleH=next.cycleH||$(next).height();next.cycleW=next.cycleW||$(next).width();if(opts.multiFx){if(opts.lastFx==undefined||++opts.lastFx>=opts.fxs.length){opts.lastFx=0;}fx=opts.fxs[opts.lastFx];opts.currFx=fx;}if(opts.oneTimeFx){fx=opts.oneTimeFx;opts.oneTimeFx=null;}$.fn.cycle.resetState(opts,fx);if(opts.before.length){$.each(opts.before,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});}var after=function(){$.each(opts.after,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});};if(opts.nextSlide!=opts.currSlide){opts.busy=1;if(opts.fxFn){opts.fxFn(curr,next,opts,after,fwd);}else{if($.isFunction($.fn.cycle[opts.fx])){$.fn.cycle[opts.fx](curr,next,opts,after);}else{$.fn.cycle.custom(curr,next,opts,after,manual&&opts.fastOnEvent);}}}opts.lastSlide=opts.currSlide;if(opts.random){opts.currSlide=opts.nextSlide;if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{var roll=(opts.nextSlide+1)==els.length;opts.nextSlide=roll?0:opts.nextSlide+1;opts.currSlide=roll?els.length-1:opts.nextSlide-1;}if(opts.pager){$.fn.cycle.updateActivePagerLink(opts.pager,opts.currSlide);}}var ms=0;if(opts.timeout&&!opts.continuous){ms=getTimeout(curr,next,opts,fwd);}else{if(opts.continuous&&p.cyclePause){ms=10;}}if(ms>0){p.cycleTimeout=setTimeout(function(){go(els,opts,0,!opts.rev);},ms);}}$.fn.cycle.updateActivePagerLink=function(pager,currSlide){$(pager).find("a").removeClass("activeSlide").filter("a:eq("+currSlide+")").addClass("activeSlide");};function getTimeout(curr,next,opts,fwd){if(opts.timeoutFn){var t=opts.timeoutFn(curr,next,opts,fwd);if(t!==false){return t;}}return opts.timeout;}$.fn.cycle.next=function(opts){advance(opts,opts.rev?-1:1);};$.fn.cycle.prev=function(opts){advance(opts,opts.rev?1:-1);};function advance(opts,val){var els=opts.elements;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}if(opts.random&&val<0){opts.randomIndex--;if(--opts.randomIndex==-2){opts.randomIndex=els.length-2;}else{if(opts.randomIndex==-1){opts.randomIndex=els.length-1;}}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.random){if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{opts.nextSlide=opts.currSlide+val;if(opts.nextSlide<0){if(opts.nowrap){return false;}opts.nextSlide=els.length-1;}else{if(opts.nextSlide>=els.length){if(opts.nowrap){return false;}opts.nextSlide=0;}}}}if($.isFunction(opts.prevNextClick)){opts.prevNextClick(val>0,opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,val>=0);return false;}function buildPager(els,opts){var $p=$(opts.pager);$.each(els,function(i,o){$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);});$.fn.cycle.updateActivePagerLink(opts.pager,opts.startingSlide);}$.fn.cycle.createPagerAnchor=function(i,el,$p,els,opts){var a=($.isFunction(opts.pagerAnchorBuilder))?opts.pagerAnchorBuilder(i,el):'<a href="#">'+(i+1)+"</a>";if(!a){return;}var $a=$(a);if($a.parents("body").length==0){$a.appendTo($p);}$a.bind(opts.pagerEvent,function(){opts.nextSlide=i;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}if($.isFunction(opts.pagerClick)){opts.pagerClick(opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,opts.currSlide<i);return false;});if(opts.pauseOnPagerHover){$a.hover(function(){opts.$cont[0].cyclePause++;},function(){opts.$cont[0].cyclePause--;});}};$.fn.cycle.hopsFromLast=function(opts,fwd){var hops,l=opts.lastSlide,c=opts.currSlide;if(fwd){hops=c>l?c-l:opts.slideCount-l;}else{hops=c<l?l-c:l+opts.slideCount-c;}return hops;};function clearTypeFix($slides){function hex(s){s=parseInt(s).toString(16);return s.length<2?"0"+s:s;}function getBg(e){for(;e&&e.nodeName.toLowerCase()!="html";e=e.parentNode){var v=$.css(e,"background-color");if(v.indexOf("rgb")>=0){var rgb=v.match(/\d+/g);return"#"+hex(rgb[0])+hex(rgb[1])+hex(rgb[2]);}if(v&&v!="transparent"){return v;}}return"#ffffff";}$slides.each(function(){$(this).css("background-color",getBg(this));});}$.fn.cycle.commonReset=function(curr,next,opts,w,h,rev){$(opts.elements).not(curr).hide();opts.cssBefore.opacity=1;opts.cssBefore.display="block";if(w!==false&&next.cycleW>0){opts.cssBefore.width=next.cycleW;}if(h!==false&&next.cycleH>0){opts.cssBefore.height=next.cycleH;}opts.cssAfter=opts.cssAfter||{};opts.cssAfter.display="none";$(curr).css("zIndex",opts.slideCount+(rev===true?1:0));$(next).css("zIndex",opts.slideCount+(rev===true?0:1));};$.fn.cycle.custom=function(curr,next,opts,cb,speedOverride){var $l=$(curr),$n=$(next);var speedIn=opts.speedIn,speedOut=opts.speedOut,easeIn=opts.easeIn,easeOut=opts.easeOut;$n.css(opts.cssBefore);if(speedOverride){if(typeof speedOverride=="number"){speedIn=speedOut=speedOverride;}else{speedIn=speedOut=1;}easeIn=easeOut=null;}var fn=function(){$n.animate(opts.animIn,speedIn,easeIn,cb);};$l.animate(opts.animOut,speedOut,easeOut,function(){if(opts.cssAfter){$l.css(opts.cssAfter);}if(!opts.sync){fn();}});if(opts.sync){fn();}};$.fn.cycle.transitions={fade:function($cont,$slides,opts){$slides.not(":eq("+opts.currSlide+")").css("opacity",0);opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.opacity=0;});opts.animIn={opacity:1};opts.animOut={opacity:0};opts.cssBefore={top:0,left:0};}};$.fn.cycle.ver=function(){return ver;};$.fn.cycle.defaults={fx:"fade",timeout:4000,timeoutFn:null,continuous:0,speed:1000,speedIn:null,speedOut:null,next:null,prev:null,prevNextClick:null,pager:null,pagerClick:null,pagerEvent:"click",pagerAnchorBuilder:null,before:null,after:null,end:null,easing:null,easeIn:null,easeOut:null,shuffle:null,animIn:null,animOut:null,cssBefore:null,cssAfter:null,fxFn:null,height:"auto",startingSlide:0,sync:1,random:0,fit:0,containerResize:1,pause:0,pauseOnPagerHover:0,autostop:0,autostopCount:0,delay:0,slideExpr:null,cleartype:!$.support.opacity,nowrap:0,fastOnEvent:0,randomizeEffects:1,rev:0,manualTrump:true,requeueOnImageNotLoaded:true,requeueTimeout:250};})(jQuery);	

	
	/**
	* jQuery.ScrollTo - Easy element scrolling using jQuery.
	* Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
	* Dual licensed under MIT and GPL.
	* Date: 5/25/2009
	* @author Ariel Flesler
	* @version 1.4.2
	*
	* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
	*/
	;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
	

// ajax upload

jQuery.extend({
	

    createUploadIframe: function(id, uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                }
                else if(typeof uri== 'string'){
                    io.src = uri;
                }
            }
            else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io			
    },
    createUploadForm: function(id, fileElementId)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
		var form = jQuery.createUploadForm(id, s.fileElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											$(io).remove();
											$(form).remove();	
											
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{
           // var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
            if(form.encoding)
			{
                form.encoding = 'multipart/form-data';				
            }
            else
			{				
                form.enctype = 'multipart/form-data';
            }			
            $(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        } 		
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
			//alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
});

function ajaxFileUpload()
	{
		$("#loading")
		.ajaxStart(function(){
			 			
			$(this).show();
			
		})
		.ajaxComplete(function(){
			
			$(this).hide();
			
		});		
		$("#preview_artwork")		
		.ajaxComplete(function(){
							  
			$("#preview_artwork").show();
			$("#preview_artwork").attr("src","/images/artwork/"+filen);
			$("#customart").attr("src","/images/artwork/thumb_"+filen);
			strlen=(filen.length);
			strlen+0;
			$("input[alt='custom']").val(filen.substring(0,strlen-4));
			$("input[alt='custom']").attr("checked","checked");
			$("input[alt='custom']").attr("id",filen);		
			$("#use_custom").attr("value","1");
			$('#uploadProgress').hide();
			$('#uploadLi').show();
		});	
		
		$.ajaxFileUpload
		(
			{
				url:'/doajaxfileupload.php',
				secureuri:false,
				fileElementId:'fileToUpload',
				dataType: 'json',
				success: function (data, status)
				{
					if(typeof(data.error) != 'undefined')
					{
						if(data.error != '')
						{
						//fail
							alert('Error uploading:\n\n1. Please check your file is a valid JPEG, GIF or PNG image\n\n2. Images must be no larger than 10Mb.');
						}else
						{
						// success
							filen=data.msg;
						return(filen);
						}
					}
				},
				error: function (data, status, e)
				{
					alert(e);
				}
			}
		)
		
		return false;

	}
	
/**
 * jQuery mousehold plugin - fires an event while the mouse is clicked down.
 * Additionally, the function, when executed, is passed a single
 * argument representing the count of times the event has been fired during
 * this session of the mouse hold.
 *
 * @author Remy Sharp (leftlogic.com)
 * @date 2006-12-15
 * @example $("img").mousehold(200, function(i){  })
 * @desc Repeats firing the passed function while the mouse is clicked down
 *
 * @name mousehold
 * @type jQuery
 * @param Number timeout The frequency to repeat the event in milliseconds
 * @param Function fn A function to execute
 * @cat Plugin
 */

jQuery.fn.mousehold = function(timeout, f) {
	if (timeout && typeof timeout == 'function') {
		f = timeout;
		timeout = 140;
	}
	if (f && typeof f == 'function') {
		var timer = 0;
		var fireStep = 0;
		return this.each(function() {
			jQuery(this).mousedown(function() {				
				fireStep = 1;
				var ctr = 0;
				var t = this;
				timer = setInterval(function() {
					ctr++;
					f.call(t, ctr);
					fireStep = 2;
				}, timeout);
			})

			clearMousehold = function() {
				clearInterval(timer);
				if (fireStep == 1) f.call(this, 1);
				fireStep = 0;
			}
			
			jQuery(this).mouseout(clearMousehold);
			jQuery(this).mouseup(clearMousehold);
		})
	}
}

	
	
