/**
 * Javascripts for Gynaika
 * 
 * author	Stijn Van Minnebruggen
 * website	www.donotfold.be
 * 
 * company	Studio Bolster
 * website	www.studiobolster.be
 * 
 */


/* GLOBAL VARS */
	
	var rootPath = '';
	var barAjaxPath = '/lib/ajax/bar.ajax.php';
	var commentsAjaxPath = '/lib/ajax/comments.ajax.php';
	var exhibitionsAjaxPath = '/lib/ajax/exhibitions.ajax.php';
	
	var barID = 'bar';
	var barSpeed = 500;
	var barOpen = false;
	
	var to, toTimer;



/* BAR FUNCTIONS */
	
	function openBar(action) {
		$.post(rootPath+barAjaxPath, {action: action}, function(r) {
			if(barOpen) {				
				$("#bar label.error span.e").hide();
				$('#'+barID).slideUp(barSpeed, function() {
					$('#'+barID).html(r).slideDown(barSpeed, function() { barIsOpen(); });
				});
			} else {
				$('#'+barID).html(r).slideDown(barSpeed, function() { barIsOpen(); });
			}
			barOpen = true;
		});
	}
	
	function showBarMsg(r) {
		$('#'+barID).html(r).slideDown(barSpeed, function() { barIsOpen(); });
		setTimeout(function() { closeBar(); }, 5000);
	}
	
	function showBarMsgCust(r, delay) {
		$('#'+barID).html(r).slideDown(barSpeed, function() { barIsOpen(); });
		if (delay != false) {
			setTimeout(function(){
				closeBar();
			}, delay);
		}
	}	
	
	function closeBar() {
		$("#bar label.error span.e").hide();
		$('#'+barID).slideUp(barSpeed, function() { $(this).empty(); });
		barOpen = false;
	}
	
	function barIsOpen() {
		$('#bar input[type="text"]:first').focus();
	}
	
	function addBarEvents() {
		
		// click actions
			$("a[href='#login'],a.btn_login").live('click', function(evt) { openBar('login'); evt.preventDefault(); });
			$("a[href='#register'],a.btn_register").live('click', function(evt) { openBar('register'); evt.preventDefault(); });
			$("a[href='#register-tnx'],a.btn_registerTnx").live('click', function(evt) { validateRegister(); evt.preventDefault(); });
			$("a[href='#newsletter'],a.btn_newsletter").live('click', function(evt) { openBar('newsletter'); evt.preventDefault(); });
			$("a[href='#newsletter-tnx'],a.btn_newsletterTnx").live('click', function(evt) { validateNewsletter(); evt.preventDefault(); });
			$("a[href='#forgot-pass'],a.btn_forgotPass").live('click', function(evt) { openBar('forgot-pass'); evt.preventDefault(); });
			$("a[href='#forgot-pass-tnx'],a.btn_forgotPassTnx").live('click', function(evt) { validateForgotpass(); evt.preventDefault(); });
			$("a[href='#closeBar'],a.btn_closeBar").live('click', function(evt) { closeBar(); evt.preventDefault(); });
		
		// hash actions
			if(location.hash == '#logout') openBar('logout');
			if(location.hash == '#login') openBar('login');
			if(location.hash == '#register') openBar('register');
			if(location.hash == '#newsletter') openBar('newsletter');
			if(location.hash == '#forgot-pass') openBar('forgot-pass');
		
	}



/* CALENDAR FUNCTIONS */
	
	function showCalendarData(el) {
		clearTimeout(to);
		hideCalendarData();
		el.css('position', 'absolute').show();
	}
	
	function hideCalendarData() {
		$('.calendar-link').next('div').hide();
		clearTimeout(to);
	}
	
	function addCalendarEvents() {
		$('.calendar-link')
			.click(
				function(evt) { evt.preventDefault(); })
			.focus(
				function() { showCalendarData($(this).next('div')); },
				function() { clearTimeout(to); to = setTimeout(function() { hideCalendarData(); }, 700); })
			.hover(
				function() { showCalendarData($(this).next('div')); },
				function() { clearTimeout(to); to = setTimeout(function() { hideCalendarData(); }, 700); })
			.next('div').focus(
				function() { clearTimeout(to); },
				function() { clearTimeout(to); to = setTimeout(function() { hideCalendarData(); }, 700); })
			.next('div').hover(
				function() { clearTimeout(to); },
				function() { clearTimeout(to); to = setTimeout(function() { hideCalendarData(); }, 700); }
			);
		
	}



/* PROJECT FUNCTIONS */
	
	function addProjectEvents() {
		$('.projectThumbs img').click(function(evt) {
			$('#project-image').attr('src', $(this).attr('rel'));
			$('#project-image-caption').html($(this).attr('alt'));
		});
	}



/* USER FUNCTIONS */
	
	function addUserEvents() {
		$('.dropdown').focus( function(){ showDropdown(); } );
		$('.dropdown').blur( function(){ clearTimeout(to); to = setTimeout(function() { hideDropdown(); }, 2000); });
			
		$('#user_dropdown li a').focus( function(){ showDropdown();  });
		$('#user_dropdown li a').focus( function(){ clearTimeout(to); to = setTimeout(function() { hideDropdown(); }, 2000); });	
	
		$('.dropdown')
			.hover(
				function() { showDropdown(); },
				function() { clearTimeout(to); to = setTimeout(function() { hideDropdown(); }, 1000); })
			.next('ul').hover(
				function() { clearTimeout(to); },
				function() { clearTimeout(to); to = setTimeout(function() { hideDropdown(); }, 1000); }
			);
		$('#userdata_submit').click(function(evt) {
			if(validateUserForm()) $('#userdata').submit();
			evt.preventDefault();
		});
		$('#saveUserSettings').click(function(evt) {
			$('#saveUserSettingsForm').submit();
			evt.preventDefault();
		});
		$('#saveUserCategories').click(function(evt) {
			$('#saveUserCategoriesForm').submit();
			evt.preventDefault();
		});
		$('#passchangeSubmit').click(function() {
			clearErrorsForFields('old', 'new', 'new2');
			if($('#old').val() == '') return showErrorForField('old');
			if($('#new').val() == '') return showErrorForField('new');
			if($('#new2').val() == '') return showErrorForField('new2');
			$('#passchangeForm').submit();
		});
		$('.workExhibitions li ul li').live('mouseover', function() {
			$(this).children('.editme').unbind().click(function() {
				
				// prepare ajax call
					var post = {
									action: 'get-exh-data',
									exh_id: $(this).parent('li').attr('rel')
								};
				
				// make ajax call
					$.post(exhibitionsAjaxPath, post, function(data) {
						$('#year').val(data.year);
						$('#title').val(data.title);
						$('#place').val(data.place);
						$('#city').val(data.city);
						$('#country').val(data.country);
						if(data.type == 'group') {
							$('#type_solo').attr('checked', false);
							$('#type_group').attr('checked', true);
						} else {
							$('#type_solo').attr('checked', true);
							$('#type_group').attr('checked', false);
						}
						$('#action').val('edit-user-exhibition');
						$('#exhibition_edit_id').val(data.id);
						$('#user_exhibitions_submit').text('aanpassen');
						$('#exhibitions_list').empty();
					}, 'json');
				
				// return false
					return false;
				
			}).show();
			$(this).children('.deleteme').unbind().click(function() {
				
				// prepare ajax call
					var post = {
									action: 'del-user-exhibition',
									exh_id: $(this).parent('li').attr('rel')
								};
				
				// make ajax call
					$.post(exhibitionsAjaxPath, post, function(data) {
							
						// add to html pool
							$('#exhibitions_list').html(data.list);
						
						// reset data
							$('#title').val('');
							$('#place').val('');
							$('#city').val('');
							$('#country').val('');
							$('#action').val('add-user-exhibition');
							$('#exhibition_edit_id').val('');
							$('#user_exhibitions_submit').text('voeg toe');
						
					}, 'json');
				
				// return false
					return false;
				
			}).show();
		});
		$('.workExhibitions li').live('mouseout', function() {
			$(this).children('.editme').hide();
			$(this).children('.deleteme').hide();
		});
		$('#user_exhibitions_submit').click(function(evt) {
			
			// validation
				clearErrorsForFields('title', 'place', 'city', 'country');
				//if($('#title').val() == '') return showErrorForField('title');
				if($('#place').val() == '') return showErrorForField('place');
				if($('#city').val() == '') return showErrorForField('city');
				if($('#country').val() == '') return showErrorForField('country');
			
			// post
				var type = ($('#type_solo').attr('checked')) ? 'solo' : 'group';
				var post = {
								year: $('#year').val(),
								title: $('#title').val(),
								place: $('#place').val(),
								city: $('#city').val(),
								country: $('#country').val(),
								type: type,
								action: $('#action').val(),
								exh_id: $('#exhibition_edit_id').val()
							};
				$.post(exhibitionsAjaxPath, post, function(data) {
					
					// add to html pool
						$('#exhibitions_list').html(data.list);
					
					// reset data
						$('#title').val('');
						$('#place').val('');
						$('#city').val('');
						$('#country').val('');
						$('#action').val('add-user-exhibition');
						$('#exhibition_edit_id').val('');
						$('#user_exhibitions_submit').text('voeg toe');
					
				}, 'json');
			
			// prevent default action
				evt.preventDefault();
			
		});
		$('#projectdata_submit').click(function() {
			var error = false;
			clearErrorsForFields('title');
			if($('#title').val() == '') return showErrorForField('title');
			if(!error) $('#projectdata').submit();
		});
		$('#photodata_submit').click(function() {
			$('#photodata').submit();
		});
	}
	
	function showDropdown() {
		clearTimeout(to);
		hideDropdown();
		$('#user_dropdown').show();
		$('.dropdown').addClass('dropdown_active');
	}
	
	function hideDropdown() {
		$('#user_dropdown').hide();
		$('.dropdown').removeClass('dropdown_active');
		clearTimeout(to);
	}



/* VALIDATION FUNCTIONS */
	
	function validateLogin() {
		clearErrorsForFields('uname', 'pass');
		if($('#uname').val() == '') return showErrorForField('uname');
		if($('#pass').val() == '') return showErrorForField('pass');
		$('#login_frm').submit();
	}
	
	function validateContact() {
		$('#contactForm').submit(function() {
			clearErrorsForFields('name_f', 'name_l', 'email', 'message', 'captcha');
			if($('#name_f').val() == '') return showErrorForField('name_f');
			if($('#name_l').val() == '') return showErrorForField('name_l');
			if(!isEmail($('#email').val())) return showErrorForField('email');
			if ($('#sumcheck').val() != $('#check').val()) return showErrorForField('sumcheck');
			if($('#message').val() == '') return showErrorForField('message');
			//if($('#captcha').val() == '') return showErrorForField('captcha');
			return true;
		});
	}
	
	function validateForgotpass() {
		
		// validate form
			clearErrorsForFields('uname', 'email');
			if($('#uname').val() == '' && !isEmail($('#email').val())) {
				showErrorForField('uname');
				showErrorForField('email');
				return false;
			}
		
		// submit form
			var p = {	action:		'forgot-pass-tnx'
						,uname:		$('#uname').val()
						,email:		$('#email').val()
					};
			$.post(rootPath+barAjaxPath, p, function(r) {
				if(barOpen) {
					$('#'+barID).slideUp(barSpeed, function() {
						$('#'+barID).html(r.resp).slideDown(barSpeed, function() { barIsOpen(); });
					});
				} else {
					$('#'+barID).html(r.resp).slideDown(barSpeed, function() { barIsOpen(); });
				}
				barOpen = true;
			}, 'json');
		
	}
	
	function validateRegister() {
		
		// validate fields
			clearErrorsForFields('name_l', 'name_f', 'uname', 'email', 'pass', 'pass_rep', 'sumcheck', 'agree_terms');
			
			if($('#name_f').val() == '') return showErrorForField('name_f');
			if($('#name_l').val() == '') return showErrorForField('name_l');
			if($('#uname').val() == '') return showErrorForField('uname');
			if(!isEmail($('#email').val())) return showErrorForField('email');
			if($('#pass').val() == '') return showErrorForField('pass');
			if($('#pass_rep').val() != $('#pass').val()) return showErrorForField('pass_rep');
			if(parseInt($('#sumcheck').val()) != parseInt($('#check').val())) return showErrorForField('sumcheck');			
			if(!$('#agree_terms').attr('checked')) return showErrorForField('agree_terms');
		
		// valid
			var p = {	action:		'register-submit'
						,name_l:	$('#name_l').val()
						,name_f:	$('#name_f').val()
						,uname:		$('#uname').val()
						,email:		$('#email').val()
						,pass:		$('#pass').val()
						,sumcheck:	$('#sumcheck').val()
						,check:		$('#check').val()
					};
			$.post(rootPath+barAjaxPath, p, function(r) {
				if(r.ok == 'false') {
					/*if(r.error == 'captcha') {
						showErrorForField('captcha');
						$('img.captcha').attr('src', $('img.captcha').attr('src')+'?'+Math.round(100*Math.random()));
					} else */
					if(r.error == 'exists') {
						showErrorForField('uname');
					}
				} else {
					if(barOpen) {
						$('#'+barID).slideUp(barSpeed, function() {
							$('#'+barID).html(r.resp).slideDown(barSpeed, function() { barIsOpen(); });
						});
					} else {
						$('#'+barID).html(r.resp).slideDown(barSpeed, function() { barIsOpen(); });
					}
					barOpen = true;
				}
			}, 'json');
		
	}
	
	function validateUserForm() {
		
		// reset errors
			clearErrorsForFields('name_f', 'name_l', 'birth_place', 'birth_date_d', 'birth_date_m', 'birth_date_y', 'phone_other', 'email', 'address_street', 'address_streetnr', 'address_postal', 'address_city', 'address_country');
		
		// validate fields
			if($('#name_f').val() == '') return showErrorForField('name_f');
			if($('#name_l').val() == '') return showErrorForField('name_l');
			if($('#birth_date_d').val() == '') return showErrorForField('birth_date_d');
			if($('#birth_date_m').val() == '') return showErrorForField('birth_date_m');
			if($('#birth_date_y').val() == '') return showErrorForField('birth_date_y');
			if($('#birth_place').val() == '') return showErrorForField('birth_place');
			if($('#phone_other').val() == '') return showErrorForField('phone_other');
			if(!isEmail($('#email').val())) return showErrorForField('email');
			if($('#address_street').val() == '') return showErrorForField('address_street');
			if($('#address_streetnr').val() == '') return showErrorForField('address_streetnr');
			if($('#address_postal').val() == '') return showErrorForField('address_postal');
			if($('#address_city').val() == '') return showErrorForField('address_city');
			if($('#address_country').val() == '') return showErrorForField('address_country');
		
		// success
			return true;
		
	}
	
	function validateNewsletter() {
		
		// validate fields
			clearErrorsForFields('name', 'email');
			if($('#name').val() == '') return showErrorForField('name');
			if(!isEmail($('#email').val())) return showErrorForField('email');
		
		// valid
			var p = {	action:		'newsletter-submit'
						,name:		$('#name').val()
						,email:		$('#email').val()
					};
			$.post(rootPath+barAjaxPath, p, function(r) {
				if(r.ok != 'false') {
					if(barOpen) {
						$('#'+barID).slideUp(barSpeed, function() {
							$('#'+barID).html(r.resp).slideDown(barSpeed, function() { barIsOpen(); });
						});
					} else {
						$('#'+barID).html(r.resp).slideDown(barSpeed, function() { barIsOpen(); });
					}
					barOpen = true;
				} else openBar('error');
			}, 'json');
		
	}
	
	function showErrorForField(fld) {
		//$('#'+fld).parent().children('span').show();
		//$('#'+fld).parent().children('span').css("display", "block");
		$('#'+fld).addClass('error').focus();
		$("label[for='"+fld+"']").addClass('error');
		return false;
	}
	
	function clearErrorForField(fld) {
		//$('#'+fld).parent().children('span').hide();
		//$('#'+fld).parent().children('span').css("display", "none");
		$('#'+fld).removeClass('error');
		$("label[for='"+fld+"']").removeClass('error');
		return true;
	}
	
	function clearErrorsForFields() {
		for(i=0; i<arguments.length; i++) clearErrorForField(arguments[i]);
	}
	
	function isEmail(v) {
		return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(v);
	}



/* COMMENTS */
	
	function addCommentEvents() {
		$('#comments-submit').click(function(evt) {
			
			// validate fields
				clearErrorsForFields('comments-name', 'comments-mail', 'comments-text', 'comments-captcha');
				if($('#comments-name').val() == '') return showErrorForField('comments-name');
				if(!isEmail($('#comments-mail').val())) return showErrorForField('comments-mail');
				if($('#comments-text').val() == '') return showErrorForField('comments-text');
				//if($('#comments-captcha').val() == '') return showErrorForField('comments-captcha');
			
			// valid
				var p = {	action:		'add-comment'
							,name:		$('#comments-name').val()
							,email:		$('#comments-mail').val()
							,website:	$('#comments-website').val()
							,text:		$('#comments-text').val()
							,link:		$('#comments-link').val()
							,t:			$('#add-comment-t').val()
							,i:			$('#add-comment-i').val()
						};
				$.post(rootPath+commentsAjaxPath, p, function(r) {
					if(r.ok == 'false') {
						if(r.error == 'spam') {
							showErrorForField('comments-text');							
							$('#err-msg').html(r.resp);
							$('#err-msg').effect("highlight", {}, 3000);

							//$('img.captcha').attr('src', $('img.captcha').attr('src')+'?'+Math.round(100*Math.random()));
							
						}
					} else {
						//clear error											
							$('#err-msg').html('');
						
						// show response
							if(r.approved == '1') {
								$('#comments').replaceWith(r.newList);
							} else {
								$('#comments').replaceWith(r.resp);
							}
						
						// empty form
							$('#comments-name').val('');
							$('#comments-mail').val('');
							$('#comments-website').val('');
							$('#comments-text').val('');
							//$('#comments-captcha').val('');
						
					}
				}, 'json');
			
		});
	}



/* NAVIGATION */
	
	function addNavEvents() {
		$('#navigation strong').next('ul').hide();
		$('#navigation strong a')
			.hover(
				function() { showNavItem($(this).parent('strong').next('ul')); },
				function() { clearTimeout(to); to = setTimeout(function() { hideNavItem(); }, 200); })
			.focus(
				function() { showNavItem($(this).parent('strong').next('ul')); },
				function() { clearTimeout(to); to = setTimeout(function() { hideNavItem(); }, 200); })
			.parent('strong').next('ul').hover(
				function() { clearTimeout(to); },
				function() { clearTimeout(to); to = setTimeout(function() { hideNavItem(); }, 200); })
			.parent('strong').next('ul').focus(
				function() { clearTimeout(to); },
				function() { clearTimeout(to); to = setTimeout(function() { hideNavItem(); }, 200); }
			);
	}
	
	function showNavItem(el) {
		clearTimeout(to);
		hideNavItem();
		el.css('position', 'absolute').show();
	}
	
	function hideNavItem() {
		$('#navigation strong').next('ul').hide();
		clearTimeout(to);
	}


	function scrollToHome(){
				
		$('#scroller_wrap').serialScroll({
			target:'#scroller',
			items:'li', // Selector to the items ( relative to the matched elements, '#sections' in this case )
			prev:'img.prev',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
			next:'img.next',// Selector to the 'next' button (absolute too)
			axis:'x',// The default is 'y' scroll on both ways
			navigation:'#slider_navigation .slide_navi li a',
			duration:400,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
			//force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
			cycle:true,
			strop: true,
			start:1,
			interval:5000,
			
			
			onBefore:function( e, elem, $pane, $items, pos ){
				/**
				 * 'this' is the triggered element 
				 * e is the event object
				 * elem is the element we'll be scrolling to
				 * $pane is the element being scrolled
				 * $items is the items collection at this moment
				 * pos is the position of elem in the collection
				 * if it returns false, the event will be ignored
				 */
				 //those arguments with a $ are jqueryfied, elem isn't.
				e.preventDefault();
				if( this.blur )
					this.blur();
				var items=$('#slider_navigation .slide_navi li');
				items.removeClass('active');
				$('#slider_navigation .slide_navi li:eq('+pos+')').addClass('active');
			},
			onAfter:function( elem ){
				//'this' is the element being scrolled ($pane) not jqueryfied
				
			}
		});
		
		$('#slider_navigation .slide_controls .play a').click(function(e){ $(this).parent().hide();$('.pause').show(); $('#scroller').trigger('stop'); e.preventDefault(); });
		$('#slider_navigation .slide_controls .pause a').click(function(e){ $(this).parent().hide();$('.play').show(); $('#scroller').trigger('start'); e.preventDefault(); });		
	}
	

	function skipToContent(){
		$("#pageInfo a").focus(function(){ $(this).parent().addClass("active"); })
		$("#pageInfo a").blur(function(){ $(this).parent().removeClass("active"); })
	}

/* PAGE LOAD */
	
	$(document).ready(function() {
		//hide subnavs first
			$("ul.inner ul").each(function(){ $(this).hide().css('top', '30px'); });
		
		// fix some IE issues
			if($.browser.msie && $.browser.version <7) $.fx.off = true;
		
		// add events
			addNavEvents();
			addBarEvents();
			addCalendarEvents();
			addProjectEvents();
			addUserEvents();
			addCommentEvents();
			validateContact();
			scrollToHome();	
			skipToContent();
	});
	


