/*
	The client side app is comprised of 5 main sections:
		
		1. iBC (iBanner Controller)
		2. S (Interface Controller)
		3. U (User Object)
		4. Pager (ajaxifies page links and build the browsers history)
		5. fn.Extensions (additional callbacks ported into jQuery to provide easy, chainable access to frequently used behaviors)
		
	1. iBC contains 8 properties and 3 methods
			path:
			th:
			bg:
			fg:
			text:
			end_date:
			user_image:
			getString:
			
			setGetString():
			updateImage():
			getShortName():
			editAsset(): 

	
	2. S contains 8 properties and 22 methods
			nextPage:
			lastPage:
			digiSteps[]:
			countSteps[]:
			stepCount:
			uploadForm:
			uploadResponses:
			
			registry(): assigns a hash link to a function
			swapPage(): the function assigned to #digisigs and #countdowns
			capsule(): the function assigned to #widgets, #toolbars, #freestuff, #screens
			details(): the function assigend to #details/[widgets, toolbars,freestuff,screens]/x
			makeNav(): called from swapPage, assigns events to prev and next buttons. TODO: step validation (can't move to next step unless something has been selected)
			digiNav(): called from makeNav if page=digisigs. organizes digisig specific bg-fg assets from server into interface, assigns itemSelect to ea.
			countNav(): called from makeNav if page=countdowns. organizes countdown specific bg-fg assets from server into interface, assigns itemSelect to ea.
			itemSelect():
			labelText():
			uploadImage():
			cropPreviewApply():
			submitComment():
			tabClick():
			steps():
			valiDate():
			overlaySize():
			position():
			pageSize():
			scrollPos():
			uploadFrame():
			fileUploaded():
			unix_tstamp():

 
*/


$(function(){
	//var J = jQuery.noConflict();

	$('.selector').css({backgroundPosition: '0px 0px'}).tabHover();
	$('img').attr('alt', 'image');
	//$('input[type="text"]').autoClear();
	S.registry();
	Pager.start('navLink', 'home');
	$.easing.def = 'easeInOutQuad';
	$('.submit span').fakeLink('submitHover');
	$('.popClose').fakeLink('closeHover');
	
	$('#log').click(function(){
		var eM = $('#uname0').val();
		var p = $('#upass0').val();
		//alert(eM+' '+p);
		if(U.isEmail($('#uname0')) != false){
			U.login(eM,p);
			$('#uname0').val('EMAIL');
			$('#upass0').val('PASSWORD');
		}
	});
	
	$('#logout').click(function(){U.logout(); });
	//$('#registerSubmit').livequery('click', function(){U.register(); });
	$('#reg-email').livequery('blur', function(){U.scrubEmail(); });
	
	//register a change event for the file upload input field 
	$('input.myUploadFile').livequery('change', function(e){ S.uploadImage($(this).val() ); });
	
	
	//$('.download').livequery('click', function(e){S.getFinalAsset(); });
	if($.browser.version == '6.0'){
		try {
		  document.execCommand("BackgroundImageCache", false, true);
		} catch(err) {}
	}
	
	

});

iBC = {
	path: '/assets/ibanner/ibanner.gif.php?',
	th: 0,
	bg: 0,
	fg: 0,
	text: "",
	complete: 0,
	end_date: 'null',
	user_image: '',
	digiText: [],
	hash: null,
	getString: null,
	setGetString: function(){
		iBC.getString = 'th='+iBC.th
				+'&bg='+iBC.bg
				+'&fg='+iBC.fg
				//+'&start_date='+iBC.start_date
				+'&end_date='+iBC.end_date
				+'&text='+iBC.text
				+'&user_image=tn'+iBC.user_image
				+'&complete='+iBC.complete
				+'&Text0='+iBC.digiText[0]
				+'&Text1='+iBC.digiText[1]
				+'&Text2='+iBC.digiText[2]
				+'&ts='+ S.unix_tstamp();		
	},
	fillData: function(e){
		iBC.th = e.th;
		iBC.bg = e.bg;
		iBC.fg = e.fg;
		iBC.text = e.text;
		iBC.user_image = e.user_image;
		iBC.digiText[0] = e.Text0;
		iBC.digiText[1] = e.Text1;
		iBC.digiText[2] = e.Text2;
		iBC.end_date = e.end_date;
		iBC.updateImage();
		//alert(e.th+'\n'+e.bg+'\n'+e.fg+'\n'+e.text+'\n'+e.user_image+'\n'+e.Text0+'\n'+e.Text1+'\n'+e.Text2+'\n'+e.end_date);
	},
	updateImage: function(){
		iBC.setGetString();
		$('#ibanner').attr('src', iBC.path+iBC.getString);
		window.scrollTo(0,295);
	},
	getShortName : function(){
		$.ajax({
			url: 'ibannerShortName.php',
			type: 'post',
			data: {'qs': iBC.getString+'&complete=1&uID='+U.uid+'&ticketId='+U.sid},
			beforeSend: function(){},
			complete: function(){},
			success: function(name){
				// fills the textareas with code for copying.
				$('.htmlClip').text('<a href="http://sheinspires.us"><img src="'+name+'" alt="SheInspires Digisigs and Countdowns" border="0"  /></a>');
				$('.pHtmlClip').text('[url=http://sheinspires.us][img]'+name+'[/img][/url]');
				$('.ezClip').text('[link='+name+'][img noborder]http://sheinspires.us/'+name+'[/img][/link]');
				$('.urlClip').text(name);
			}
		});
	},
	editAsset: function(id){
		$.ajax({
			url: '',
			type: 'post',
			data: 'id='+id+'&qs='+iBC.getString,
			beforeSend: function(){},
			complete: function(){},
			success: function(data){
				
			}
		})
	},
	clearData: function(){
		iBC.th = 0,
		iBC.bg = 0,
		iBC.fg = 0,
		iBC.text = "",
		iBC.complete = 0,
		iBC.end_date = 'null',
		iBC.user_image = '',
		iBC.digiText = [],
		iBC.hash = null,
		iBC.getString = null
	}
};

S = {
	nextPage: '',
	lastPage: '',
	corners: '<div class="bL"><div class="bR"><div class="tL"><div class="tR"></div></div></div></div>',
	digiSteps: ['Select your background',
		    'Customize your digisig with text and your own image',
		    'Customize your digisig with a personalized image',
		    'Here is your Digisig!'],
	countSteps: ['Select a theme for your special occasion',
		     'Select your background',
		     'Select a ticker to countdown to the big day',
		     'Customize your countdown with text and your own image',
		     'Input the date of your big day',
		     'Here is your Countdown!'],
	stepCount: 0,
	fileTypes: 'jpg,png,gif,jpeg',
	uploadForm: function(){
		var ts = S.unix_tstamp();
		return '<form action="inc/upload2.php" method="post" enctype="multipart/form-data" id="myUploadForm" name="myUploadForm">'
		    +'<input id="fileTypes" type="hidden" name="filetypes" value="jpg,png,gif,jpeg" />'
		    +'<div id="listOfInputs">'
			+'<input size="1" type="file" id="img" class="myUploadFile file" name="file1" value="Select your file" />'
			+'<input type="hidden" name="time_stamp" value="'+ts+'" />'
		    +'</div>'
		+'</form>'
	},
	uploadResponses:
		'<div id="uploadAlert"></div>'
		+'<div id="listOfFiles"></div>'
		+'<div class="responseMsg"><div id="cropPreview"></div>'
		+'<form id="cropForm" action="inc/upload2.php" method="post">'
                                        +'<input type="hidden" name="x1" value="0" id="x1" />'
                                        +'<input type="hidden" name="y1" value="0" id="y1" />'
                                        +'<input type="hidden" name="x2" value="90" id="x2" />'
                                        +'<input type="hidden" name="y2" value="75" id="y2" />'
                                        +'<input type="hidden" name="w" value="90" id="w" />'
                                        +'<input type="hidden" name="h" value="75" id="h" />'
                                        +'<input type="hidden" name="image_name" id="image_name" />'
		    +'<input type="submit" name="upload_thumbnail" value="apply" id="apply_thumb" />'
		+'<div id="response"><div id="loading">uploading now. . .</div><ul></ul></div>'
		+'</form></div>',
	//Registers all the ajax links on this page (She Inspires) with Pager.watchForChange function
	registry: function(){
		//Home and Sub pages
		Pager.register('home', S.capsule);
		Pager.register('digisigs', S.swapPage);
		Pager.register('countdowns', S.swapPage);
		//Pager.register(/digisigs/[0-9], S.steps);
		//Pager.register(/countdowns/[0-9], S.steps);
		Pager.register('widgets', S.capsule);
		Pager.register('freestuff', S.capsule);
		Pager.register('toolbars', S.capsule);
		Pager.register('screens', S.capsule);
		Pager.register('forgot', S.forgotPWPage);
		Pager.register('register', S.registerPage);
		Pager.register('myaccount', S.accountPage);
		Pager.register('goodbye', U.logout);
		Pager.register(/details\/widgets/, S.details);
		Pager.register(/details\/freestuff/, S.details);
		Pager.register(/details\/toolbars/, S.details);
		Pager.register(/details\/screens/, S.details);
		Pager.register(/details\/countdowns/, S.details);
		Pager.register(/details\/digisigs/, S.details);
	},
	//between [free stuff, widgets, toolbars, screensavers] and [digisigs, countdowns]
	forgotPWPage: function(){
		S.nextPage = Pager.getHashFromURL(location.hash);
		$('#indexAndSub').empty();
		$('#forget').clone().removeClass('popup').find('.popClose').remove().end().appendTo($('#indexAndSub')).wrap(S.corners);
		
		//give cloned fields unique ids
		$('#indexAndSub input[name="femail"]').attr('id', 'f-email');
		
		//$('input[type="text"], input[type="password"]').autoClear();
		
		$('#indexAndSub #forgotSubmit').click(function(){
			if(U.isEmail($('#f-email')) != false){U.recoverPW($('#f-email').val());}
		});
		Pager.ajaxifyLinks('navLink');
		S.lastPage = S.nextPage;
	},
	registerPage: function(){
		S.nextPage = Pager.getHashFromURL(location.hash);
		$('#indexAndSub').empty();
		$('#register').clone().attr('id', 'regInline').removeClass('popup').find('.popClose').remove().end().appendTo($('#indexAndSub')).wrap(S.corners);
		
		//give cloned registration fields unique ids
		$('#indexAndSub input[name="reg-name"]').attr('id', 'reg-name');
		$('#indexAndSub input[name="reg-lastname"]').attr('id', 'reg-lastname');
		$('#indexAndSub input[name="reg-email"]').attr('id', 'reg-email');
		$('#indexAndSub input[name="reg-password"]').attr('id', 'reg-p');
		$('#indexAndSub input[name="password_confirm"]').attr('id', 'reg-pc');
		$('#indexAndSub input[name="reg-allow"]').attr('id', 'reg-allow');
		
		//$('input[type="text"], input[type="password"]').autoClear();
		
		$('#indexAndSub .regSub').attr('id', 'inlineRegSub').removeAttr('class').click(function(){
			if(U.isEmail($('#reg-email')) != false){U.register();}
		});
		
		S.lastPage = S.nextPage;
	},
	swapPage: function(pName,e){
		S.nextPage = pName;
		iBC.user_image = '';
		S.tabClick('selector', pName);
		
		$('#indexAndSub').empty();
		
		$('#'+pName+'Bin').clone().find('.urCodez').attr('id','urCodez').removeAttr('class').end().appendTo('#indexAndSub').show();
		$('#ibanner').remove();
		$('<img src="assets/ibanner/ibanner.gif.php" id="ibanner" class="iBan" />').prependTo($('#indexAndSub #'+pName+'Bin .banContain'));
		if(!e){e=null;
			iBC.clearData();
			$('.digiMake').text('create!');
			$('.countMake').text('create!');
		}else{
			iBC.fillData(e);
			$('#indexAndSub #'+S.nextPage+'Bin .initHero').fadeOut(300, function(){$('#indexAndSub #'+S.nextPage+'Bin .banContain').show();});
			
			$('.digiMake').text('save changes');
			$('.countMake').text('save changes');
		}
		
		//$('input[type="text"]').autoClear();
		$('<div id="uploadForm"></div>').appendTo($('#'+pName+'UploadImage'));
		//alert($('#uploadForm #myUploadForm'));

		$('#uploadForm').append(S.uploadForm());

		
		//append image crop forms to the app flow
		$('#'+pName+'UploadImage').append(S.uploadResponses);
			$('form#cropForm').ajaxForm({
					data: {'time': new Date()},
					success: function(){iBC.updateImage();}
			});
		S.makeNav();
		
		//Check if user is logged in.. if not clone login, forgotPW and register forms to the last step of the work flow and attach events/ajax callbacks to the 'forms'
		if(U.firstName == null) S.insertFlowForms();
		
		$('select[name="Text0"]').change(function(){iBC.digiText[0] = $(this).val(); iBC.updateImage(); });
		$('select[name="Text1"]').change(function(){iBC.digiText[1] = $(this).val(); iBC.updateImage(); });
		$('select[name="Text2"]').change(function(){iBC.digiText[2] = $(this).val(); iBC.updateImage(); });
		
		$('#'+S.nextPage+'Step0').fadeIn(300);
		$('.imgareaselect-outer, .imgareaselect-selection, .imgareaselect-border1, .imgareaselect-border2').remove();
		
		
		$('.digiMake').click(function(){iBC.complete=1;if(U.uid){ iBC.getShortName(); $('#indexAndSub .logRegCall').hide(); $('#urCodez').show();} });
		$('.countMake').click(function(){iBC.complete=1;if(U.uid){ iBC.getShortName();  $('#indexAndSub .logRegCall').hide(); $('#urCodez').show();} });
		
		Pager.ajaxifyLinks(pName+'Link');
		//Pager.ajaxifyLinks('nextStep');
		S.lastPage = S.nextPage;
		//alert('');
	},
	insertFlowForms: function(){
		// Places login, regristration and forget pw Elements specifically into the Digisigs and Countdowns work flow.
		$('#login').clone().attr('id', 'logInline').removeClass('popup').find('.popClose').attr('id','logClose').end().appendTo($('#indexAndSub .logRegCall')).wrap(S.corners);
		$('#register').clone().attr('id', 'regInline').removeClass('popup').find('.popClose').attr('id','regClose').end().appendTo($('#indexAndSub .logRegCall')).wrap(S.corners);
		$('#forget2').clone().attr('id', 'forgetInline').removeClass('popup').find('.popClose').attr('id','forClose').end().appendTo($('#indexAndSub .logRegCall')).wrap(S.corners);

		//give cloned fields unique ids
		$('#indexAndSub input[name="femail"]').attr('id', 'f-email');

		//give cloned login fields unique ids
		$('#indexAndSub input[name="user"]').attr('id', 'log-u');
		$('#indexAndSub input[name="password"]').attr('id', 'log-p');

		//give cloned registration fields unique ids
		$('#indexAndSub input[name="reg-name"]').attr('id', 'reg-name');
		$('#indexAndSub input[name="reg-lastname"]').attr('id', 'reg-lastname');
		$('#indexAndSub input[name="reg-email"]').attr('id', 'reg-email');
		$('#indexAndSub input[name="reg-password"]').attr('id', 'reg-p');
		$('#indexAndSub input[name="password_confirm"]').attr('id', 'reg-pc');
		$('#indexAndSub input[name="reg-allow"]').attr('id', 'reg-allow');

		//assign close anim to 'close' elements
		if($.browser.msie){
			$('#regClose').click(function(){$('#regInline').hide(50, function(){
							$('#indexAndSub .logRegCall').animate({height:50}, 200);
							}); });
			$('#logClose').click(function(){$('#logInline').hide(50, function(){
							$('#indexAndSub .logRegCall').animate({height:50}, 200);
							}); });
			$('#forClose').click(function(){$('#forgetInline').hide(50, function(){
							$('#indexAndSub .logRegCall').animate({height:50}, 200);
							}); });	
		}else{
			$('#regClose').click(function(){$('#regInline').hide('drop', {direction: 'up'}, 200, function(){
							$('#indexAndSub .logRegCall').animate({height:50}, 200);
							}); });
			$('#logClose').click(function(){$('#logInline').hide('drop', {direction: 'up'}, 200, function(){
							$('#indexAndSub .logRegCall').animate({height:50}, 200);
							}); });
			$('#forClose').click(function(){$('#forgetInline').hide('drop', {direction: 'up'}, 200, function(){
							$('#indexAndSub .logRegCall').animate({height:50}, 200);
							}); });
		}

		//assign reveal anims to 'Register', 'Login' and 'Forgot password' 'links'
		if($.browser.msie){
		$('#indexAndSub .logBtn')
			.attr('id', 'inlineLogBtn')
			.removeClass('logBtn')
			.click(function(){
				$('#regInline').hide();
				$('#forgetInline').hide();
				//$('#indexAndSub .regBtn').trigger('click');
				$('#indexAndSub .logRegCall').animate({height:300}, 200, function(){
						$('#logInline').show();
					});
		});
		$('#indexAndSub .regBtn')
			.attr('id', 'inlineRegBtn')
			.removeClass('regBtn')
			.click(function(){
				$('#logInline').hide();
				$('#forgetInline').hide();
				//$('#indexAndSub .logBtn').trigger('click');
				$('#indexAndSub .logRegCall').animate({height:450}, 200, function(){
						$('#regInline').show();
					});
		});
		$('#indexAndSub .forBtn')
			.attr('id', 'inlineForBtn')
			.removeClass('forBtn')
			.click(function(){
				$('#logInline').hide();
				$('#regInline').hide();
				//$('#indexAndSub .logBtn').trigger('click');
				$('#indexAndSub .logRegCall').animate({height:300}, 200, function(){
						$('#forgetInline').show();
					});
		});
		}else{
			$('#indexAndSub .logBtn')
				.attr('id', 'inlineLogBtn')
				.removeClass('logBtn')
				.click(function(){
					$('#regInline').hide();
					$('#forgetInline').hide();
					//$('#indexAndSub .regBtn').trigger('click');
					$('#indexAndSub .logRegCall').animate({height:300}, 200, function(){
							$('#logInline').show('drop', {direction: 'up'}, 200);
						});
			});
			$('#indexAndSub .regBtn')
				.attr('id', 'inlineRegBtn')
				.removeClass('regBtn')
				.click(function(){
					$('#logInline').hide();
					$('#forgetInline').hide();
					//$('#indexAndSub .logBtn').trigger('click');
					$('#indexAndSub .logRegCall').animate({height:450}, 200, function(){
							$('#regInline').show('drop', {direction: 'up'}, 200);
						});
			});
			$('#indexAndSub .forBtn')
				.attr('id', 'inlineForBtn')
				.removeClass('forBtn')
				.click(function(){
					$('#logInline').hide();
					$('#regInline').hide();
					//$('#indexAndSub .logBtn').trigger('click');
					$('#indexAndSub .logRegCall').animate({height:300}, 200, function(){
							$('#forgetInline').show('drop', {direction: 'up'}, 200);
						});
			});	
		}


		//assign submit events to submit buttons
		$('#indexAndSub .logSub').attr('id', 'inlineLogSub').removeAttr('class').click(function(){
			//perform login only if email input evaluates as true
			if(U.isEmail($('#log-u')) != false){ U.login($('#log-n').val(), $('#log-p').val());}
		});
		$('#indexAndSub .regSub').attr('id', 'inlineRegSub').removeAttr('class').click(function(){
			
			if(U.isEmail($('#reg-email')) != false){U.register();}
		});
		$('#indexAndSub #forgotSubmit').click(function(){
			if(U.isEmail($('#f-email')) != false){U.recoverPW($('#f-email').val());}
		});

		//$('#logInline .popTitle').remove();
		//$('#regInline .popTitle').remove();
		//$('#forgetInline .popTitle').remove();
		//$('input[type="text"], input[type="password"]').autoClear();

	},
	makeNav: function(){
		//this is called when iether digisigs or countdowns is selected
		//Sets up prev next button behaviors
		//Also, if countdowns is selected, the var S.theme is created
		$('#indexAndSub #'+S.nextPage+'Bin .step').each(function(i){
			
			//number of steps in the asset creation flow
			var len = $('#indexAndSub #'+S.nextPage+'Bin .step').length -1;
			
			//assign each step div a unique id based on the step in the process
			$(this).attr('id', S.nextPage+'Step'+i);
			
			//Set Option unique Id's attach click events with callback to S.countNav for Countdowns
			//S.theme var is created here!
			if(S.nextPage == 'countdowns'){
				$('.option', this).each(function(e){
					var step=i;
					var option = e;
						$(this).attr('id', 'step'+i+'opt'+e).fadeLink(100).click(function(){
								S.theme = option;
								S.countNav(option);
							});	
				});
			}
			
			//Next Step button behaviors
			$('.nextStep', this).click(function(){
					if(i <= len){ // limits fading of content in steps to the length of steps
						var $this = $(this);
						if(i > 3){//alert(S.valiDate($('#date').attr('value')));
							if(S.valiDate($('#date').attr('value')) == 1){
								S.steps(i);
							}
						}else if((S.theme || S.theme == 0)||(S.nextPage == 'digisigs')){
								S.steps(i);
								//if(i > 3)iBC.complete = 1; iBC.getShortName();
						}else{alert('choose theme first!');}
					}
					});
			
			//Previous Step Button behaviors
			$('.prevStep', this).click(function(){S.steps(i, 1); });	
			$('.nextStep, .prevStep').fadeLink(100);
			
			//User Input Field behavior
			$('#'+S.nextPage+'Text').keyup(function(){S.labelText($(this).attr('value')) });//add keyup function to countdowns text input
			//add keyup func to digiName input
			$('#digiName').keyup(function(){S.labelText($(this).attr('value')) });
		});
		if(S.nextPage == 'digisigs') S.digiNav(3);
	},
	digiNav: function(){
		var type = S.nextPage;
		var steps = $('.step').length;
		$('#'+type+'Step1 .option, #'+type+'Step2 .imageScroll .option').remove();
		iBC.th = 3;
		var $bg = $('#bgBin .theme3').clone();
		var $tick0 = $('#tickBin .theme0').clone().slice(0,3);
		var $tick1 = $('#tickBin .theme1').clone().slice(0,2);
		var $tick2 = $('#tickBin .theme2').clone().slice(0,8);
		var count = 0;

		$bg.insertAfter('#'+type+'Step'+count+' .topStep');
		$bg.each(function(index, el){
			var mod = index%3;
			var theme = count;
			$(this).attr('id', 'bg'+index).fadeLink(100).unbind('click').click(function(e){S.itemSelect(index, 'bg', theme);});
			if(mod==2)count++;
		});
		count = 1;
		$tick0.prependTo('#'+type+'Step1 .imageScroll');
		$tick1.prependTo('#'+type+'Step1 .imageScroll');
		$tick2.prependTo('#'+type+'Step1 .imageScroll');
		$tick0.each(function(index, el){$(this).attr('id', 'tick'+index).fadeLink(100).unbind('click').click(function(){S.itemSelect((index +1), 'fg');});});
		$tick1.each(function(index, el){$(this).attr('id', 'tick'+index).fadeLink(100).unbind('click').click(function(){S.itemSelect((index+4), 'fg');});});
		$tick2.each(function(index, el){$(this).attr('id', 'tick'+index).fadeLink(100).unbind('click').click(function(){S.itemSelect((index+6), 'fg');});});

		iBC.updateImage();
	},
	countNav: function(option){
		var type = S.nextPage;
		iBC.th = option;
		iBC.fg = 0;
		var shift =11;
		if(option == 0){var slice = 3;}else if(option==1){var slice=2;}else if(option==2){var slice=8;}
		var steps = $('.step').length;
		$('#'+type+'Step1 .option, #'+type+'Step2 .imageScroll .option').remove();

		var $bg = $('#bgBin .theme'+option).clone();
		
		var $tick = $('#tickBin .theme'+option).clone().slice(0,slice);
		var $tickGeneric = $('#tickBin .theme'+option).clone().slice(slice);

		$bg.prependTo('#'+type+'Step1 .imageScroll');
		$bg.each(function(index, el){
			$(this).attr('id', 'bg'+index).fadeLink(100).unbind('click').click(function(e){S.itemSelect(index, 'bg');});
		});
		$tick.prependTo('#'+type+'Step2 .imageScroll');
		$tickGeneric.prependTo('#'+type+'Step2 .imageScroll');
		$tick.each(function(index, el){$(this).attr('id', 'tick'+index).fadeLink(100).unbind('click').click(function(){
			if(option==1)S.itemSelect((index+4), 'fg');
			if(option==2)S.itemSelect((index+6), 'fg');
			if(option==0)S.itemSelect((index+1), 'fg');
			}); });
		$tickGeneric.each(function(index, el){$(this).attr('id', 'tick'+index).fadeLink(100).unbind('click').click(function(){S.itemSelect((index+shift), 'fg'); }); });

		iBC.updateImage();
		$('#indexAndSub #'+S.nextPage+'Bin .initHero').fadeOut(300, function(){$('#indexAndSub #'+S.nextPage+'Bin .banContain').fadeIn(300);});
	},
	steps: function(step, direction){
		if(iBC.th == 2){ S.countSteps[4]='Input the date of your next birthday';}else{
			S.countSteps[4]='Input the date of your big day';
		}
		if(S.nextPage == 'digisigs'){var steps = S.digiSteps;}else{var steps = S.countSteps;}
		//when moving forward
		if(direction == null){var n = step+1; var num = step + 2;}
		//when moving backwards
		else{var n = step-1; var num = step; /*$('.remove').trigger('click')*/ ;}

		S.stepCount = n;
		//alert(step+' '+S.nextPage);
		//alert(num+' '+S.nextPage+'\n'+(num === 3 && (S.nextPage == 'digisigs')) );
		if(num == 4 && (S.nextPage == 'countdowns')){$('.imgareaselect-outer, .imgareaselect-selection, .imgareaselect-border1, .imgareaselect-border2').show();}		
		else if((S.nextPage == 'digisigs') && num == 3){$('.imgareaselect-outer, .imgareaselect-selection, .imgareaselect-border1, .imgareaselect-border2').show();}		else{
			$('.imgareaselect-outer, .imgareaselect-selection, .imgareaselect-border1, .imgareaselect-border2').hide();
			}
		if($.browser.msie){
			$('#'+S.nextPage+'Step'+step).hide(20, function(){$('#'+S.nextPage+'Step'+n).show();});
		}else{
			$('#'+S.nextPage+'Step'+step).fadeOut(50, function(){$('#'+S.nextPage+'Step'+n).fadeIn(250);});
		}
		
		$('#indexAndSub .stNum').text(num); 
		$('#indexAndSub .stName').text(steps[n]);
		window.scrollTo(0,295);
	},
	//Exit/enter animation for hero and capsules
	capsule: function(){
	//this is for when a tab has been clicked
		S.nextPage = Pager.getHashFromURL(location.hash);
		//all currentPage-specific Els are hidden, copied to the #elBin div
		$('#indexAndSub').empty();
		//Elements for the Tab just clicked are dropped in
		//first the hero, 
		$('#hero'+S.nextPage).clone().appendTo('#indexAndSub').show();//.show('drop', {direction:'left', easing:'easeOutBounce'}, 600);
		$('#hero'+S.nextPage+' a').addClass(S.nextPage+'Link');
		// .. then the capsules	
		$('.'+S.nextPage+'Capsule').clone().appendTo('#indexAndSub').each(function(i, e){
			$('a', this).addClass(S.nextPage+'Link');
			$(this).hide().fadeIn(500+ (i*250));//.show('drop', {direction:'left', easing:'easeOutBounce'}, 800 + (i*200));
		});
		Pager.ajaxifyLinks(S.nextPage+'Link');
		//currentPage is set to the tab just clicked
		//all tabs go to original position, current Tab is animated to active state.
		S.tabClick('selector', S.nextPage);
		S.lastPage = S.nextPage;
	},
	details: function(){
		S.nextPage = Pager.getHashFromURL(location.hash);
		var bits = S.nextPage.split('/');
		var a = bits[0];
		var b = bits[1];
		var c = bits[2];
		var cString = ' '+bits[2];
		if(b=='widgets'){var short_name = 'widget'}
			else if(b=='toolbars'){short_name = 'tool'}
		short_name = short_name + cString;
		window.scrollTo(0,0);
		//tab is updated
		S.tabClick('selector', bits[1]);
		
		//hero area is updated / rendered
		$('#indexAndSub').empty();
		$.ajax({
			url: 'tpl/assetDetails.php',
			type: 'post',
			data: {'short_name': short_name},
			beforeSend: function(){},
			complete: function(){},
			success: function(data){
				$('#indexAndSub').prepend(data);
				$('#indexAndSub #submit').click(function(){
					var msg = $('#indexAndSub textarea#comment-text').attr('value');
					var name = $('#indexAndSub input[name="commenter-name"]').val();
					var asset_id = $('#indexAndSub input[name="asset_id"]').val();
					S.submitComment(msg, name, asset_id, short_name);
				});
				$('input[name="commenter-name"]').autoClear();
				$('#indexAndSub textarea#comment-text').charCount('charCount', 500);
				$('#bc1').text(b).attr('href', b).addClass('');
				$('#bc2').attr('href', S.nextPage).addClass('');
				$('#'+bits[1]+'_'+bits[2]+' a').addClass(bits[0]+bits[1]+'Link');
				$('#indexAndSub .commentPane').empty().load('tpl/commentDetails.php', {'short_name': short_name});
				//unveiled ajax links are processed..
				Pager.ajaxifyLinks(bits[0]+bits[1]+'Link');
				Pager.ajaxifyLinks('aLink');
				S.lastPage = S.nextPage;
			}
		});
	},
	accountPage: function(){
		S.nextPage = Pager.getHashFromURL(location.hash);
		
		$('#indexAndSub').empty();
		$('<div id="editPane">'+
			'<h2>These are the Digisigs and Countdowns you have made</h2>'+
			//'<p>Click on an image to edit it.</p>'+
			'<div id="digis"><h2>Digisigs</h2></div>'+
			'<div id="counts"><h2>Countdowns</h2></div>'+
			'</div>').appendTo($('#indexAndSub'));
		
		if(U.uid != null){U.getAssets();} //renderAssets is called from this function

		S.lastPage = S.nextPage;
	},
	renderAssets: function(){
		var digi = U.digisigs; var count = U.countdowns;
		$.each(digi, function(i){
			$('<img class="editLink" src="/ibanner/'+U.digisigs[i].shortName+'.gif" />')
				//.click(function(){S.swapPage('digisigs', U.digisigs[i].querystring); })
				.appendTo('#digis');
		});
		$.each(count, function(i){
			$('<img class="editLink" src="ibanner/'+U.countdowns[i].shortName+'.gif" />')
				//.click(function(){S.swapPage('countdowns', U.countdowns[i].querystring); })
				.appendTo('#counts');
		});
		//Pager.ajaxifyLinks('editLink');

	},
	itemSelect: function(option, step, theme){
		var frame=0;
		if(step == 'bg'){
			iBC.bg = option;
			if(S.nextPage=='digisigs'){}else{frame=1;}
			
			$('#indexAndSub #'+S.nextPage+'Bin .initHero').fadeOut(300, function(){$('#indexAndSub #'+S.nextPage+'Bin .banContain').fadeIn(300);});
		}else if(step == 'fg'){
			if(S.nextPage=='digisigs'){frame=1;}else{frame=2;}
			iBC.fg = option;
		}
		iBC.updateImage();
	},
	labelText: function(text){
		var array = text.split('');
		$(array) . each(function(i, e){
			if(e == '<'){e = '&lt;'}
			if(e == '>'){e = '&gt;'}
			//if(e == '.' || e == ';'){e = ' '}
			array[i] = e;
		});
		iBC.text = array.join('');
		iBC.updateImage();
	},
	uploadImage: function(value){
		/*var path = 'file:///'+ $('.myUploadFile').val();
		var imgCheck = new Image();
		imgCheck.src = path;
		var x = imgCheck.width;
		var y = imgCheck.height;
		alert(path+' '+x+' '+y);*/
		if(value) {
			// check file extension for approved file types
			if (S.fileTypes.match(value.toLowerCase().substr(value.toLowerCase().lastIndexOf('.')+1))) {
				//iFrame style of img upload, the only way
				$('#loading').show(100);
				//iFrame is inserted into the DOM and set as the form's target before it is actually submit
				//this is not truly ajax, but rather old-school hidden iframe bootleg ajax.
				$('form#myUploadForm').attr('target', S.uploadFrame()).submit();	// submit the form

			}
			else {
				$('#uploadAlert').empty().text('file type ' + value.substr(value.lastIndexOf('.')+1) + ' not allowed');
				return false;
			}
		}
		else alert("No file to upload.");
	},
	cropPreviewApply: function(img, selection){
		var scaleX = 90 / selection.width; 
		var scaleY = 75 / selection.height;
		var imgH = $('.nameOfFile img:first-child').height();
		var imgW = $('.nameOfFile img:first-child').width();

		
		$('#cropPreview img').stop().css({ 
			width: Math.round(scaleX * imgW) + 'px', 
			height: Math.round(scaleY * imgH) + 'px',
			marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
			marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
		});

		$('#x1').stop().val(selection.x1);
		$('#y1').stop().val(selection.y1);
		$('#x2').stop().val(selection.x2);
		$('#y2').stop().val(selection.y2);
		$('#w').stop().val(selection.width);
		$('#h').stop().val(selection.height);
	},

	submitComment: function(text, name, asset_id, short_name){
		var bits = S.nextPage.split('/');
		if(bits[1] == 'tools'){
			bits[2] = parseInt(bits[2], 10) + 4;
		}
		if($('input[name="commenter-name"]').val() == 'Your Name Here' || $('input[name="commenter-name"]').val() == '' ){
			$('input[name="commenter-name"]').alertAnim();
		}else if($('textarea#comment-text').val() == ''){
			$('textarea#comment-text').alertAnim();
		}else{
		$.ajax({
			url: 'comment.php',
			type: 'post',
			data: {'comment-msg' : text, 'commenter-name': name, 'asset_id': asset_id},
			beforeSend: function(){},
			complete: function(){},
			success: function(data){
				$('#indexAndSub .commentPane').empty().load(
					'tpl/commentDetails.php',
					{'short_name': short_name},
					function(){
					    $('#indexAndSub #comForm').hide('drop',{direction: 'up'}, 600, function(){$(this).remove(); $('#indexAndSub #thankYou').fadeIn(600);});
					}
					);
				}
		});
		}
	},
	tabClick: function(elClass, actTarget){
		var target = actTarget || '';
		var theClass = elClass || '';
				$('.'+theClass)
				.stop()
				.removeClass('activeNav')
				.css({backgroundPosition: '0px 0px'});
				if($.browser.msie && $.browser.version == '6.0'){
					$('#tab'+actTarget).addClass('activeNav');
				}else{
				$('#tab'+target)
				.css({backgroundPosition: '158px -115px'})
				.animate({backgroundPosition: '(0px -115px)'}, 150, function(){$(this).addClass('activeNav');});
				}
				$('h6', this)
				.animate({color: '#ffffff'}, 100);
	},
	valiDate: function(date){
		var x = new Date();
		var today = $.fn.formatDate(x, 'MM/dd/yyyy');
		var valid = date.match(/\d{2}\/\d{2}\/\d{4}/);
		var past = $.fn.compareDates(today, 'MM/dd/yyyy', valid, 'MM/dd/yyyy');
		var exists = $.fn.isDate(date, 'MM/dd/yyyy');
		if(!valid){$.fn.smoothAlert('valDate', 'oops! wrong date format. please use the format shown above.');}
			else if(valid && !exists){$.fn.smoothAlert('valDate', 'This date does not exist. please enter a valid date.');}
			else if(past == 1){$.fn.smoothAlert('valDate', 'This date has already passed. please enter a future date.');}
			else{iBC.end_date = date; iBC.updateImage(); return true;}
	},
	overlaySize: function(){
		var position = S.scrollPos();
		var xy = S.pageSize();
		$('#overlay, #oWindow').css({
			height: xy[1],
			width: xy[0],
			left: position[1],
			top: position[0],
			opacity: .7
		});
	},
	position: function(el){
		var position = S.scrollPos();
		var pagesize = S.pageSize();
		var elLeft = (pagesize[0]/2) - ($('#'+el).width() / 2);
		var elTop = (pagesize[1]/2) - ($('#'+el).height() / 2);
			$('#overlay, #oWindow').css({left: position[1] + 'px', width: pagesize[0] + 'px'});
				  if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
					$("#overlay, #oWindow").css({top: position[0] + 'px'});
					}
			$('#'+el).css({left: (elLeft + position[1]) + 'px', top: (elTop + position[0]) + 'px'});
	},
	pageSize: function(){
		  var de = document.documentElement;
		  var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		  var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
		  arrayPageSize = [w,h];
		  return arrayPageSize;
	},
	scrollPos: function(){
		var top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
		var left = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
		arrayScrollPos = [top, left];
		return arrayScrollPos;
	},
	uploadFrame: function(){
		// build iframe to receive form data, remove previous iFrame first
		$(".uploadFrame").remove();
		$("<div class='uploadFrame'><iframe src='about:blank' id='myFrame' name='myFrame'></iframe></div>").insertAfter('body');
		// onload iFrame, call S.fileUploaded function
		$("iframe#myFrame").load(function(){
				S.fileUploaded(this);
		});
		// return iFrame id for form target
		return 'myFrame';

	},
	fileUploaded: function(id){
		// determine platform syntax
		if (id.contentDocument)
			var d = id.contentDocument;
		else if (id.contentWindow) 
			var d = id.contentWindow.document;
		else 
			var d = window.frames[id].document;
		
		// trim name of file returned to iFrame
		var json = JSON.parse( d.body.innerHTML );
		//var json = eval('"' + d.body.innerHTML + '"');
		var _img_name = json.original_image;
		var _session = json.session_id;
		var _type = json.image_type;
		var _h = json.image_height;
		var _w = json.image_width;
		iBC.user_image = json.original_image;

		// hide ajax loader
		$('#loading').hide();
		
		// check if php mime file type is approved
		if (json.error) {
			$('#uploadAlert')
				.empty()
				.append(json.error)
				.animate({backgroundColor: '#ffffff'}, 2000, function(){$(this)
				     .animate({backgroundColor: '#ffcccc'}, 50, function(){$(this)
					      .animate({backgroundColor: '#ffffff'}, 3000);
					      });
				     });
			return false;
		}else {
			//$('#'+S.nextPage+'UploadImage').append(S.uploadResponses);
			// build file thumb display
			_newFile = $('<div class="nameOfFile"></div>');
    
			$('#image_name').attr({value: _img_name});
			    
			// add crop preview image
			crop_ = new Image();
			$(crop_)
			    .appendTo('#cropPreview')
			    .attr({id:_img_name+'Crop',src:'tmp/'+_session+'/'+_img_name, title:_img_name });
			$('#cropPreview').fadeIn(300);
    
			// add user image
			if(_h > 75 || _w > 90){
			img_ = new Image();
    
			$(img_)
			    .appendTo(_newFile)
			    .attr({id:_img_name, src:'tmp/'+_session+'/'+_img_name, title:_img_name })
			    .imgAreaSelect({aspectRatio:'1.2:1', onSelectChange:S.cropPreviewApply});
			    
			//text alert
			$('#uploadAlert')
			    .html('<div><strong>Your file '+_img_name+' needs to be cropped</strong></div>'
				+'<div><strong>Select an area from the original image to include in the final image.</strong></div>')
			    //.attr({id:'cropText'})
			    .animate({backgroundColor: '#ffffff'}, 2000, function(){$(this)
				     .animate({backgroundColor: '#ffcccc'}, 50, function(){$(this)
					      .animate({backgroundColor: '#ffffff'}, 3000);
					      });
				     });
			}
    
			// add remove icon
			remove_ = '<div><input value="delete" type="button" /></div>';
			$(remove_)
			    .insertBefore('#apply_thumb')
			    .attr({className: 'remove', title:_img_name })
			    .click(function(){$.get("inc/upload2.php?delete=" + _img_name, function(){
						var $this = remove_;
						$('#response ul').append('<div><li><span>' +_img_name + '</span> deleted.</li></div>');
		
						// remove input.file by searching for input with filename as class
						$('.imgareaselect-outer, .imgareaselect-selection, .imgareaselect-border1, .imgareaselect-border2').remove();
						$("input[@className*='"+ _img_name + "']").parent().remove();
						// remove the first input.file also.  another will be added by addInput()
						$("#listOfInputs .fake_wrap:eq(0)").remove();
						$('#uploadAlert').empty();
						$('#cropPreview').fadeOut(300).empty();
						$('#listOfInputs').show();
						$('#apply_thumb').fadeOut(250);
						$('#uploadForm').append(S.uploadForm());
						$('.nameOfFile').remove();
						$('.remove').remove();
						$('.uploadFrame').remove();
						iBC.updateImage();
					})
				});

			// add to dom
			$("#listOfFiles").prepend(_newFile);
			$('#apply_thumb').fadeIn(250);
			$('#uploadForm').empty();
			// display file info in ajax response section
			$('#response ul').append('<li><span>' + _img_name + '</span></li>');
    
	    }
	},
	unix_tstamp: function(){
		return parseInt(new Date().getTime().toString().substring(0, 10))
	}
}

V = {
	loggedInView: function(){
		$('.loggedOut').hide();
		$('.loggedIn').show();
		$('#loggedInUser').text(U.firstName);
		if(iBC.complete == 1){
			iBC.getShortName();
			if($.browser.msie){
				$('#indexAndSub .logRegCall').hide(50, function(){
					$('#urCodez').show();
				});
			}else{
				$('#indexAndSub .logRegCall').hide('drop',{direction:'down'}, 500, function(){
					$('#urCodez').show('drop',{direction:'down'},500);
				});
			}

		}
		window.scrollTo(0,0);
	},
	loggedOutView: function(){
		$('.loggedIn').hide();
		$('.loggedOut').show();
		$('#loggedInUser').text('');
		U.clearData();
		iBC.clearData();
		$('#indexAndSub').empty().html('<h1>Thanks for visiting! Come back soon!</h1>');
		window.scrollTo(0,0);
	}
}

U = {
	//  User Object //
	uid: null,
	sid: null,
	firstName: null,
	lastName: null,
	email: null,
	digisigs: null,
	countdowns: null,
	
	login: function(n,p){
		if(n){var u = n;}else{
		u = $('#log-u').val();
		}
		if(p){var pw = p}else{
		pw = $('#log-p').val();
		}
		$.ajax({
			url: 'ajaxCalls/logInProcess.php',
			type: 'post',
			data: 'email='+u+'&pass1='+p+'&ts='+S.unix_tstamp(),
			beforeSend: function(){},
			complete: function(){},
			success: function(json){
				var data = JSON.parse(json);
				if(data.error){
					alert(data.error);
				}else{
					U.uid = data.member_id;
					U.sid = data.ticketID;
					U.firstName = data.fname;
					U.lastName = data.lname;
					U.email = data.email;
					//U.getAssets();
					V.loggedInView();
				}
			}
		});
	},
	logout: function(){
		V.loggedOutView();
	},
	recoverPW: function(em){
		$.ajax({
			url: 'ajaxCalls/recoverPassword.php',
			type: 'post',
			data: 'email='+em,
			beforeSend: function(){},
			complete: function(){},
			success: function(msg){
				//var data = JSON.parse(msg);
				alert('If you\'re email is valid, you will receive your password shortly.');
			}
		});
	},
	register: function(){
		firstName = 	$('#reg-name').val();
		lastName = 	$('#reg-lastname').val();
		email = 	$('#reg-email').val();
		pw = 		$('#reg-p').val();
		var pwc = 	$('#reg-pc').val();
		allowContact=	$('#allow-contact').val();
		
		if(!firstName){$.fn.smoothAlert('noMatch', "please enter a first name");}
		else if(!lastName){$.fn.smoothAlert('noMatch', "please enter a last name");}
		else if(!email){$.fn.smoothAlert('noMatch', "please enter an email");}
		else if(pw != pwc){$.fn.smoothAlert('noMatch', "Passwords don't match");}
		else{
			$.ajax({
				type: "post",
				url: "ajaxCalls/registerProcess.php",
				data: "fname="+firstName+'&lname='+lastName+'&email='+email+'&pass1='+pw+'&pass2='+pwc+'&allowOffers='+allowContact+'&ts='+S.unix_tstamp(), 
				beforeSend: function(){},
				complete: function(){},
				success: function(json){
					//var data = JSON.parse(json);
					if(json == 'SUCCESS:'){
						alert(json);
					}else{
						U.login(email,pw);
					}
					if(S.nextPage == 'register'){
						$('#regInline').hide('drop',{direction: 'down'},400,function(){
							$('<div class="popTitle">Thank you for registering! you are now logged in.</div>').appendTo($('#indexAndSub'));
						})
					}
				}
			});
		}

	},
	scrubEmail: function(){
		var testEmail = $('#reg-email').val();
		$.ajax({
			method:'get',
			url:'ajaxCalls/isEmailUnique.php',
			data:'email='+testEmail+'&ts='+S.unix_tstamp(),
			success: function(data){
				switch(data){
				case 'FALSE' :
					break;
				case 'TRUE' :
					break;
				case 'INVALID' :
					break;
				}
			}
		})
		
	},

	getAssets: function(){
		$.ajax({
			url: 'ajaxCalls/getQsFromHash.php',
			type: 'post',
			data: 'member_id='+U.uid+'&ticketID='+U.sid,
			beforeSend: function(){},
			complete: function(){},
			success: function(json){
				var data = JSON.parse(json);
				//alert(data.countdowns[0].shortName+'\n'+data.countdowns[0].querystring);
				if(data.error){alert(data.error); }
				else{
					U.digisigs = data.digisigs;
					U.countdowns = data.countdowns;
					S.renderAssets();
				}
			}
		})
	},
	getCountdown: function(){
		this.method = '/inc/getCountdown.php';
	},
	isEmail: function(el){
		var email = $(el).attr('value');
		var id = $(el).attr('id');
		var yes = email.match(/^[A-Za-z0-9]+\w*([._-][a-zA-Z0-9]+)*@[A-Za-z0-9]+([._-][a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$/);
		if(!yes){
			$(el).alertAnim().val('Enter a valid email'); return false;
			}else{
				return true;}
	},
	clearData: function(){
		U.uid=null;
		U.firstName=null;
		U.lastName=null;
		U.email=null;
		U.digisigs=null;
		U.countdowns= null;
	}
}



 //Ajax Paging System by J.Sambells ported to JQuery by R.Sweeten
Pager = {
	//a helper to make callbacks
	makeCallback: function(method, target){
		return function(){method.apply(target,arguments);}
	},
	
	//A URL hash listener used to trigger registered methods based on hashes
	lastHash: '',
	callbacks: [],
	safariHist: false,
	ieHist: false,
	ajaxLinks: '',
	ajaxRoot: '',
	absolutePath: '',	
		
	start: function(ajaxLinksClass, startingHash, ajaxRoot){
		this.ajaxLinks = ajaxLinksClass;
		this.ajaxRoot = ajaxRoot || '';		
		if($.browser.safari){
			this.safariHist = [];
		} else if($.browser.msie){
			$('body').append('<iframe id="ieHist" name="ieHist"></iframe>');
			//this grabs the iframe elements properly..
			var e = $(frames['ieHist']);
			//this makes the iframe <document> data accessible to this script!!
			//solution found here:
			//http://webdevel.blogspot.com/2007/03/iframes-and-jquery-working-with.html
			this.ieHist = e[0];

		}
		this.getAbsolute();
		this.ajaxifyLinks(ajaxLinksClass);
		thisPage = this.getLocation();
		if(!location.hash && !startingHash) {startingHash = '';}
		ajaxHash = this.getHashFromURL(location.hash) || startingHash;
		this.addBackButtonHash(ajaxHash);
		var watcherCallback = this.makeCallback(this.watchLocationForChange, this);
		window.setInterval(watcherCallback, 200);
		
	},
	ajaxifyLinks: function(elClass){
		var links = $('.'+elClass);
		$.each(links, function(i){
			var processed = $(this).hasClass('modified');
			if($(this).hasClass(elClass) && !processed){
			var h = $(this).attr('href');
			var x = h.match(Pager.absolutePath);
			if(x){h = h.slice(Pager.absolutePath.length);}
			$(this).attr('href', Pager.convertURLToHash(h));
			$(this).click(function(){
						if(this.href && this.href.indexOf('#') > -1){
							Pager.addBackButtonHash(Pager.getHashFromURL(this.href));
						}
					}).addClass('modified');		
			}	
		});
	},	
	addBackButtonHash: function(ajaxHash){
		if(!ajaxHash) return false;
		if(this.safariHist !== false) {
			if(this.safariHist.length == 0){
				this.safariHist[window.history.length] = ajaxHash;
			}else{
				this.safariHist[window.history.length+1] = ajaxHash; 	
			}
			return true;
		}else if(this.ieHist !== false){
			this.ieHist.document.execCommand('Stop');
			this.ieHist.location.href = 'fakepage.htm?hash='+ajaxHash+'&title='+document.title;
			return true;
		}else{
			var timeoutCallback = this.makeCallback(function(){
					if(this.getHashFromURL(window.location.href) != ajaxHash){
						window.location.replace(location.href + '#' + ajaxHash);	
					}
				},this);
			setTimeout(timeoutCallback, 200);
			return true;
		}
		return false;
	},
	
	
	watchLocationForChange: function(){
		var newHash;
		if(this.safariHist !== false){
			if(this.safariHist[history.length]){
				newHash = this.safariHist[history.length];
			}
		}else if(this.ieHist !== false){
			newHash = this.ieHist.location.href.split('&')[0].split('=')[1];
		}else if(location.hash != ''){
			newHash = this.getHashFromURL(window.location.href);	
		}
		if(newHash && this.lastHash != newHash){
			if(this.ieHist !== false && this.getHashFromURL(window.location.href) != newHash){
				location.hash = newHash;
			}
			try{
				this.execListeners(newHash);
			}catch(e){
				alert(e);
			}
			this.lastHash = newHash;
		}
	},
	
	register: function(regex,method,context){
		var obj = {'regex':regex};
		if(context){
			obj.callback = function(matches){
				method.apply(context, matches);
			};
		}else {
			obj.callback = function(matches){
				method.apply(window, matches);
			};
		}
		this.callbacks.push(obj);
			
	},
	
	convertURLToHash: function(url){
		if(!url){
			return '#' + url;	
		}else if(url.indexOf('#') != -1){
			return url.split('#')[1];
		}else {
			if(url.indexOf('://') != -1){
				url = url.match(/:\/\/[^\/]+(.*)/)[1];	
			}
			return '#' + url.substr(this.ajaxRoot.length)
		}
	},
	

	getHashFromURL: function(url){
		if(!url || url.indexOf('#') == -1){return '';}
		return url.split('#')[1];
	},
	
	getLocation: function(){
		if(!window.location.hash) {
			var url = {host:null, hash:null};
			if(window.location.href.indexOf('#') > -1){
				parts = window.location.href.split('#')[1];
				url.domain = parts[0];
				url.hash = parts[1];
			}else{
				url.domain = window.location;
			}
			return url;
		}
		return window.location;
	},
	
	execListeners: function(hash){
		for(var i in this.callbacks){
			if((matches = hash.match(this.callbacks[i].regex))){
				this.callbacks[i].callback(matches);	
			}
		}
	},
	
	getAbsolute: function(){
		var path = location.pathname;
		var a = path.length;
		var b = window.location.href.indexOf('m/') + 1 + a;
		this.absolutePath = window.location.href.substring(0, b);
	}

}



$.fn.extend ({
	MONTH_NAMES: new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),
	DAY_NAMES: new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat'),
	LZ: function(x){return(x<0||x>9?"":"0")+x},
	charCount: function(targetEl, max){
			$(this).keyup(function(){
				var count = $(this).val().length;
				if(count > max){
					$(this).val($(this).val().substring(0, max));
					$('#'+targetEl).text('0');
				}else{
					$('#'+targetEl).text(max - count);
				}
			});	
	},
	alertAnim: function(){
		return this.each(function(){
			$(this).stop().animate({backgroundColor: '#ffcccc'}, 20, function(){$(this)
					      .animate({backgroundColor: '#ffffff'}, 1200);
					      });
				     });	
	},
	tabHover: function(){
		return this.each(function(){
			$(this).hover(function(){
				if($.browser.msie && $.browser.version == '6.0'){
					$(this).stop().css('background-position', '0px -57px');
					//alert('yes');
				}else{$(this)
					.stop()
					.animate({backgroundPosition: '(0px -57px)'}, 120);
				}
				$('h6', this).stop().animate({color: '#f78218'}, 100);
				}, 
				function(){if($.browser.msie && $.browser.version == '6.0'){
				   $(this).stop().css('background-position', '0px 0px');
				   }else{$(this)
					.stop()
					.animate({backgroundPosition: '(0px 0px)'}, 160)
				   }
				//.effect('bounce', {direction: 'up', distance: 2, times: 3}, 50);
				$('h6', this).stop().animate({color: '#f4a762'}, 50); 
				});
		});
	},
	fakeLink: function(newClass){
		return this.each(function(){
		$(this).hover(function(e){$(this).addClass(newClass);}, function(e){$(this).removeClass(newClass);});
		});
	},
	fadeLink: function(speed){
		return this.each(function(){
			if($.browser.msie){
				$(this).hover(function(e){$(this).stop().css({opacity: .5}); }, function(e){$(this).stop().css({opacity: 1});});
			}else{
				$(this).hover(function(e){$(this).stop().fadeTo(speed, .5); }, function(e){$(this).stop().fadeTo(speed, 1);});
			}
		});
	},
	autoClear: function(){
		return this.each(function(){
		    var value = $(this).val();
		    $(this).blur(function(){
				if($(this).val() == ''){
				$(this).val(value);
				}
		    });
		    $(this).focus(function(){$(this).val(''); });
		    
		});
	},
	smoothAlert: function(el, msg){
			$('#'+el)
				.text(msg)
				.css({visibility: 'visible', opacity: 1})
				.animate({opacity: 1}, 1500, function(){$(this)
				.animate({opacity: 0}, 1500, function(){$(this).css('visibility', 'hidden');});})
	},
	popOpen: function(el){
		return this.each(function(){
			$(this).click(function(){
				var pagesize = S.pageSize();
				var top = pagesize[1] / 2;
				var left = pagesize[0] / 2;
				var elTop = top - ($('#'+el).height() / 2);
				var elLeft = left - ($('#'+el).width() / 2);
					if (typeof document.body.style.maxHeight === 'undefined') {//if IE 6
					  $('body','html').css({height: '100%', width: '100%'});
					  $('html').css('overflow','hidden');
					  if (document.getElementById('hideSelect') === null) {//iframe to hide select elements in ie6
						$('body').prepend("<iframe id='hideSelect'></iframe><div id='overlay'></div><div id='oWindow'></div>");
						$('#overlay').popClose();
					  }
					}else{//all others
					  if(document.getElementById('overlay') === null){
						$('body').prepend("<div id='overlay'></div>");
						S.overlaySize();
						$('#overlay').click(popClose)
							.hide()
							.fadeIn(100, function(){
								$('#'+el+' .popClose').click(popClose);
								$('#'+el)
									.appendTo('body')
									.css({top: elTop, left: elLeft})
									//.attr({id: el+'Active'})
									.fadeIn(600);
								
							});
					  }
					} 
				window.onresize = function(){ S.overlaySize(); S.position(el);}
				window.onscroll = function(){S.position(el);}
				function popClose(){
					$('#'+el)
						.hide('puff', {easing: 'easeInOutCubic'}, 300, function(){
							$('#oWindow, #overlay, #hideSelect').trigger('unload').unbind().fadeOut(150, function(){$(this).remove();});
							});
					$('#'+el+' .popClose').unbind('click');
					return false;
				}
	
			});
		});
	},

	mailBit: function(){	
		return this.each(function(){
			var tld_ = new Array()
			tld_[0] = "com";
			tld_[1] = "org";
			tld_[2] = "net";
			tld_[3] = "ws";
			tld_[4] = "info";
			tld_[10] = "co.uk";
			tld_[11] = "org.uk";
			tld_[12] = "gov.uk";
			tld_[13] = "ac.uk";
			var topDom_ = 13;
			var m_ = "mailto:";
			var a_ = "@";
			var d_ = ".";
			var href = $(this).attr('title').split('/');
			$(this).attr({'href': m_+href[0]+a_+href[1]+d_+tld_[href[2]], 'title': ''});
		});
	},
	compareDates: function(date1,dateformat1,date2,dateformat2) {
	var d1=$.fn.getDateFromFormat(date1,dateformat1);
	var d2=$.fn.getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	},
	
	formatDate: function(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=$.fn.LZ(M);
	value["MMM"]=$.fn.MONTH_NAMES[M-1];
	value["NNN"]=$.fn.MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=$.fn.LZ(d);
	value["E"]=$.fn.DAY_NAMES[E+7];
	value["EE"]=$.fn.DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=$.fn.LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=$.fn.LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=$.fn.LZ(value["K"]);
	value["kk"]=$.fn.LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=$.fn.LZ(m);
	value["s"]=s;
	value["ss"]=$.fn.LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	},

	isDate: function(val,format) {
		var date= $.fn.getDateFromFormat(val,format);
		if (date==0) { return false; }
		return true;
	},
	_isInteger: function(val) {
		var digits="1234567890";
		for (var i=0; i < val.length; i++) {
			if (digits.indexOf(val.charAt(i))==-1) { return false; }
			}
		return true;
	},
	_getInt: function(str,i,minlength,maxlength) {
		for (var x=maxlength; x>=minlength; x--) {
			var token=str.substring(i,i+x);
			if (token.length < minlength) { return null; }
			if ($.fn._isInteger(token)) { return token; }
			}
		return null;
	},
	getDateFromFormat: function(val,format) {
		val=val+"";
		format=format+"";
		var i_val=0;
		var i_format=0;
		var c="";
		var token="";
		var token2="";
		var x,y;
		var now=new Date();
		var year=now.getYear();
		var month=now.getMonth()+1;
		var date=1;
		var hh=now.getHours();
		var mm=now.getMinutes();
		var ss=now.getSeconds();
		var ampm="";
		
		while (i_format < format.length) {
			// Get next token from format string
			c=format.charAt(i_format);
			token="";
			while ((format.charAt(i_format)==c) && (i_format < format.length)) {
				token += format.charAt(i_format++);
				}
			// Extract contents of value based on format token
			if (token=="yyyy" || token=="yy" || token=="y") {
				if (token=="yyyy") { x=4;y=4; }
				if (token=="yy")   { x=2;y=2; }
				if (token=="y")    { x=2;y=4; }
				year=$.fn._getInt(val,i_val,x,y);
				if (year==null) { return 0; }
				i_val += year.length;
				if (year.length==2) {
					if (year > 70) { year=1900+(year-0); }
					else { year=2000+(year-0); }
					}
				}
			else if (token=="MMM"||token=="NNN"){
				month=0;
				for (var i=0; i<$.fn.MONTH_NAMES.length; i++) {
					var month_name=$.fn.MONTH_NAMES[i];
					if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
						if (token=="MMM"||(token=="NNN"&&i>11)) {
							month=i+1;
							if (month>12) { month -= 12; }
							i_val += month_name.length;
							break;
							}
						}
					}
				if ((month < 1)||(month>12)){return 0;}
				}
			else if (token=="EE"||token=="E"){
				for (var i=0; i<$.fn.DAY_NAMES.length; i++) {
					var day_name=$.fn.DAY_NAMES[i];
					if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
						i_val += day_name.length;
						break;
						}
					}
				}
			else if (token=="MM"||token=="M") {
				month=$.fn._getInt(val,i_val,token.length,2);
				if(month==null||(month<1)||(month>12)){return 0;}
				i_val+=month.length;}
			else if (token=="dd"||token=="d") {
				date=$.fn._getInt(val,i_val,token.length,2);
				if(date==null||(date<1)||(date>31)){return 0;}
				i_val+=date.length;}
			else if (token=="hh"||token=="h") {
				hh=$.fn._getInt(val,i_val,token.length,2);
				if(hh==null||(hh<1)||(hh>12)){return 0;}
				i_val+=hh.length;}
			else if (token=="HH"||token=="H") {
				hh=$.fn._getInt(val,i_val,token.length,2);
				if(hh==null||(hh<0)||(hh>23)){return 0;}
				i_val+=hh.length;}
			else if (token=="KK"||token=="K") {
				hh=$.fn._getInt(val,i_val,token.length,2);
				if(hh==null||(hh<0)||(hh>11)){return 0;}
				i_val+=hh.length;}
			else if (token=="kk"||token=="k") {
				hh=$.fn._getInt(val,i_val,token.length,2);
				if(hh==null||(hh<1)||(hh>24)){return 0;}
				i_val+=hh.length;hh--;}
			else if (token=="mm"||token=="m") {
				mm=$.fn._getInt(val,i_val,token.length,2);
				if(mm==null||(mm<0)||(mm>59)){return 0;}
				i_val+=mm.length;}
			else if (token=="ss"||token=="s") {
				ss=$.fn._getInt(val,i_val,token.length,2);
				if(ss==null||(ss<0)||(ss>59)){return 0;}
				i_val+=ss.length;}
			else if (token=="a") {
				if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
				else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
				else {return 0;}
				i_val+=2;}
			else {
				if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
				else {i_val+=token.length;}
				}
			}
		// If there are any trailing characters left in the value, it doesn't match
		if (i_val != val.length) { return 0; }
		// Is date valid for month?
		if (month==2) {
			// Check for leap year
			if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
				if (date > 29){ return 0; }
				}
			else { if (date > 28) { return 0; } }
			}
		if ((month==4)||(month==6)||(month==9)||(month==11)) {
			if (date > 30) { return 0; }
			}
		// Correct hours value
		if (hh<12 && ampm=="PM") { hh=hh-0+12; }
		else if (hh>11 && ampm=="AM") { hh-=12; }
		var newdate=new Date(year,month-1,date,hh,mm,ss);
		return newdate.getTime();
	}
});

