/* nivo slider */

$(window).load(function() {
    $('#slider').nivoSlider({
        effect:'random', // Specify sets like: 'fold,fade,sliceDown'
        slices:15, // For slice animations
        boxCols: 8, // For box animations
        boxRows: 4, // For box animations
        animSpeed:500, // Slide transition speed
        pauseTime:5000, // How long each slide will show
        startSlide:0, // Set starting Slide (0 index)
        directionNav:false, // Next & Prev navigation
        directionNavHide:true, // Only show on hover
        controlNav:true, // 1,2,3... navigation
        controlNavThumbs:false, // Use thumbnails for Control Nav
        controlNavThumbsFromRel:false, // Use image rel for thumbs
        controlNavThumbsSearch: '.jpg', // Replace this with...
        controlNavThumbsReplace: '_thumb.jpg', // ...this in thumb Image src
        keyboardNav:true, // Use left & right arrows
        pauseOnHover:true, // Stop animation while hovering
        manualAdvance:false, // Force manual transitions
        captionOpacity:0.8, // Universal caption opacity
        prevText: 'Prev', // Prev directionNav text
        nextText: 'Next', // Next directionNav text
        beforeChange: function(){}, // Triggers before a slide transition
        afterChange: function(){}, // Triggers after a slide transition
        slideshowEnd: function(){}, // Triggers after all slides have been shown
        lastSlide: function(){}, // Triggers when last slide is shown
        afterLoad: function(){} // Triggers when slider has loaded
    });
});


$(document).ready(function () {

	$('#subBarForm').submit(function() {
		
		$('#subBarForm input[type=text]').each(function () {
			if ($(this).val() == $(this).attr('rel')) $(this).addClass('error');
			else $(this).removeClass('error');		
		});
		
		if ($('#subBarForm input.error').length) return false;
		
	});

});


/* encode email */
$(document).ready(function () {

	$('a.mailto').each(function () {
	
		var data = $(this).attr('rel').split('|');
		var email = data[0] + '@' + data[1];
	
		$(this).attr('href', 'mailto:' + email);
		$(this).html(email);
	
	});

});


/* contact form validation */

$(document).ready(function(){ 

	$('#contactForm').submit(function () {
	

		var firstname = $('#firstname');
		var lastname = $('#lastname');
		var email = $('#email');
		var country = $('#country option:selected');
		var postcode = $('#postcode');
		var subject = $('#subject');
		var question = $('#question');

		validIt(firstname, 'first name');
		validIt(lastname, 'last name');
		if (validIt(email, 'email')) {
		
			if (!validate(email.val())) {
				email.addClass('error'); 
				email.parent().children('div.notice').remove();
				email.parent().append('<div class="notice">Please enter a valid email address.</div>');			
			} else {
				email.removeClass('error'); 
				email.parent().children('div.notice').remove();			
			}
		
		}
		validOpt(country, 'country');		

		if (validIt(postcode, 'postcode')) {

			if (!validateInt(postcode.val())) {
				postcode.addClass('error'); 
				postcode.parent().children('div.notice').remove();
				postcode.parent().append('<div class="notice">Please enter a valid postcode.</div>');			
			} else {
				postcode.removeClass('error'); 
				postcode.parent().children('div.notice').remove();			
			}
		
		}
		

		validIt(subject, 'subject');
		validIt(question, 'question');

		
		if ($('#contactForm div.notice').length) return false;
		else return true;
	
	});

});


/* subscription form validation */

$(document).ready(function(){ 

	$('#subForm').submit(function () {
	
		var email = $('#email');
		var firstname = $('#firstname');
		var lastname = $('#lastname');
		var optins = $('input.optin:checked');
		var age = $('#age:checked');
		var tc = $('#tc:checked');
		var pp = $('#pp:checked');
		
		if (validIt(email, 'email')) {
		
			if (!validate(email.val())) {
				email.addClass('error'); 
				email.parent().children('div.notice').remove();
				email.parent().append('<div class="notice">Please enter a valid email address.</div>');			
			} else {
				email.removeClass('error'); 
				email.parent().children('div.notice').remove();			
			}
		
		}
		
		validIt(firstname, 'first name');
		validIt(lastname, 'last name');
		
		if (!optins.length) {
			$('.optinlist').children('div.notice').remove();
			$('.optinlist').append('<div class="notice">Please select at least one mailing list to subscribe to.</div>');		
		} else {
			$('.optinlist').children('div.notice').remove();
		}
		
		if (!age.length || !tc.length || !pp.length) {
			$('.confirmlist').children('div.notice').remove();
			$('.confirmlist').append('<div class="notice">Please confirm that you are of legal drinking age and have read and accepted the terms and conditions and privacy policy.</div>');		
		} else {
			$('.confirmlist').children('div.notice').remove();
		}
		
		
		if ($('#subForm div.notice').length) return false;
		else return true;
	
	});

});


function validIt(elm, lbl) {

	if (!elm.val()) {
		elm.addClass('error'); 
		elm.parent().children('div.notice').remove();
		elm.parent().append('<div class="notice">Please enter your ' + lbl + '.</div>');
		return false;
	} else {
		elm.removeClass('error'); 
		elm.parent().children('div.notice').remove();
		return true;
	}

}

function validOpt(elm, lbl) {

	if (!elm.val()) {
		elm.addClass('error'); 
		elm.parent().parent().children('div.notice').remove();
		elm.parent().parent().append('<div class="notice">Please enter your ' + lbl + '.</div>');
		return false;
	} else {
		elm.removeClass('error'); 
		elm.parent().parent().children('div.notice').remove();
		return true;
	}

}


function validate(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   }
   return true;
}

function validateInt(int) {
   var reg = /^([0-9])+$/;
   if(reg.test(int) == false) {
      return false;
   }
   return true;
}

/* superfish dropdown menu */
$(document).ready(function(){ 
	$("ul.sf-menu").superfish(); 
}); 


/* back to top link auto hide */
$(document).ready(function() {
	
	if ($('#content .mainContent').height() < 700) {
		$('div.top').hide();
	}

});


/* manual sideNav highlight */
$(document).ready(function () {

	var maintitle = $('#content .mainContent h1').html();

	$('#menu-sidebar-news li a').each(function () {
		
		if ($(this).html() == 'Latest News' && maintitle == 'News') $(this).parent().addClass('active');
		if ($(this).html() == maintitle) $(this).parent().addClass('active');
		
	});
	
	$('.sideNav ul').find('ul.children').hide();	
	
	$('.sideNav ul li.current_page_item a').each(function () {	
		
		//console.log($(this).html());

		if ($(this).html() == maintitle && $(this).parent().find('ul').length) {
			$(this).parent().find('ul.children').show();				
		}

		if ($(this).html() == maintitle && $(this).parent().parent().hasClass('children')) {
			$(this).parent().parent().parent().find('ul.children').show();			
		}
	
 	});

});

/* select drop down box nav */

$(document).ready(function () {

	$('select.selectNav').change(function () {
	
		if ($(this).val()) window.location = $(this).val();
	
	});

});

/* flexible layout */
$(document).ready(function () {

	if ($('#content .images').children().size() == 0) {
	
		$('#content .content').addClass('fullwidth');
	
	}

});


/* font resizer */
$(document).ready(function () {
 
    //min font size
    var min=9; 
 
    //max font size
    var max=16;
     
    //grab the default font size
    var reset = $('#content').css('fontSize');

    //font resize these elements
    var elm = $('#content .content, .sideNav a, .images .image'); 
     
    //set the default font size and remove px from the value
    var size = str_replace(reset, 'px', '');
     
    //Increase font size
    $('.utilBar a.plus').click(function() {
         
        //if the font size is lower or equal than the max value
        if (size<=max) {
             
            //increase the size
            size++;
             
            //set the font size
            elm.css({'fontSize' : size});
        }
         
        //cancel a click event
        return false;  
         
    });
 
    $('.utilBar a.minus').click(function() {
 
        //if the font size is greater or equal than min value
        if (size>=min) {
             
            //decrease the size
            size--;
             
            //set the font size
            elm.css({'fontSize' : size});
        }
         
        //cancel a click event
        return false;  
         
    });
     
    //Reset the font size
    $('a.fontReset').click(function () {
         
        //set the default font size
         elm.css({'fontSize' : reset});    
    });
         
});
 
//A string replace function
function str_replace(haystack, needle, replacement) {
    var temp = haystack.split(needle);
    return temp.join(replacement);
}
	
/* toggle input */	
$(document).ready(function () {

	$('input.toggle').focus(function () {
	
		var val = $(this).val();
		var rel = $(this).attr('rel');
	
		if (val == rel) $(this).val(''); 
		
	}).blur(function () {
	
		var val = $(this).val();
		var rel = $(this).attr('rel');
	
		if (val == '') $(this).val(rel); 
		
	});

	$('input.sitesearch').focus(function () {
	
		$(this).data('bg', $(this).css('background-image'));
		$(this).css({'background-image': 'none'}); 
		
	}).blur(function () {
	
		$(this).css({'background-image': $(this).data('bg')}); 
	});

});	
	
/* mosaic */	
	
$(document).ready(function () {
	
	//layout setting
	var col = 13;  //it will calculate the row based on total of items
	var width = 50;
	var height = 50;
	var delay = 300;
	var speed = 500;
				
	//for processing
	var currentrow = 1;
	var index = 1;
	var row = Math.ceil($('#mosaics a').length / col);

	//Recalculate CSS based on layout setting
	//+3 = fix ie6 issue
    $('#mosaics').css({'width': (width * col + 3) , 'height': (height * row)});
    $('#mosaics a').css({'width': width , 'height': height});
		
	//initialize all the mosaic data
	$('#mosaics a').each(function () {
		
		//determine the position of the popup
		if (index >= ((col * currentrow) - 1) && index <= (col * currentrow) && currentrow != row) {
			$(this).data('pos', 'l');			
		} else if (index >= ((col * row) - col) && index <= ((col * row) - 2)) {
			$(this).data('pos', 'rb');
		} else if (index >= ((col * row) - 1) && index <= (col * row)) {
			$(this).data('pos', 'lb');
		} else {
			$(this).data('pos', 'r');
		}
			
		//save data
		$(this).data('index', index);
		$(this).data('width', $(this).children('img').width());
		$(this).data('height', $(this).children('img').height());
			
		//increment value

		if (index % (col) == 0) {
			currentrow++;
		}			
		index++;
					
		//reconstruct the HTML!
		$(this).append('<div class="full"></div><div class="overlay"></div>');
		$(this).css({'backgroundImage': 'url(' + $(this).children('img').attr('src') + ')'});
		$(this).children('div.full').css({'backgroundImage': 'url(' + $(this).children('img').attr('src') + ')', 'backgroundPosition': $(this).css('backgroundPosition'), 'width': width, 'height': width});
		$(this).children('div.overlay').css({'width': width, 'height': width});			
		$(this).children('img').remove();
			
	});
	
	//action
	$('#mosaics a').hover(
		function () {
				
			//call the custom method
			$(this).css({'z-index':40}).slideitout(delay, speed);
			$('#mosaics .overlay').show();
			
		},
			
		function () {
			$(this).css({'z-index':0});
			$('#mosaics .overlay').hide();
			$('#mosaics a').children('div.full').hide().css({width:width, height:height, left:0, top:0});									
		}
	);
		
	
});
	
	
jQuery.fn.slideitout = function (delay, speed) {

	//get initial value
    var pos = this.data('pos');	    
    var left = this.position()['left'];
    var top = this.position()['top'];
    var width = this.width();
	    
    //assign position accordingly to the code
    if (pos == 'r') {
    	left = 0;
    	top = 0;	    
    } else if (pos == 'l') {	    
    	left = width * (-2);
    	top = 0;
    } else if (pos == 'rb') {	    		    		
    	left = 0;
    	top = width * (-1);	    			    
    } else if (pos == 'lb') {	    
	    left = width * (-2);
	    top = width * (-1);			    
    }
	    
    //do it!
   	this.children('div.full').delay(delay).show().animate({width: this.data('width'), height: this.data('height'), left: left, top:top}, speed);
    	
}	

