$(document).ready(function(){

	$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

	$("ul.topnav li span").click(function() { //When trigger is clicked...

		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() {
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});
	
	
	var config = {
		sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
		interval: 100, // number = milliseconds for onMouseOver polling interval
		over: makeTall, // function = onMouseOver callback (REQUIRED)
		timeout: 400, // number = milliseconds delay before onMouseOut
		out: makeShort // function = onMouseOut callback (REQUIRED)
	};
	
	$("ul.topnav li").hoverIntent(config).hover(function() {
			$(this).addClass("subhover"); //On hover over, add class “subhover”
			}, function(){	//On Hover Out
				$(this).removeClass("subhover"); //On hover out, remove class “subhover”
	});
	
	$('a.mailme').defuscate();
	
	$('#quotebuttonLayer').click(function() {
			location.href = 'quote.html';
	});
	
	$("#datepicker").datepicker();
	
	$(".randomimg").imBannerRotater({
		images: 'img1.jpg,img2.jpg,img3.jpg,img4.jpg,img5.jpg,img6.jpg,img7.jpg,img8.jpg,img9.jpg,img10.jpg,img11.jpg,img12.jpg,img13.jpg,img14.jpg,img15.jpg',
		base_path: 'images/cycle/'
	});
					
	setupValidation();				
});

function setupValidation(){
	
	$(".lcheck").each(
					  
		function( intIndex ){
			$(this).inputTip({
			goodText: "Validated",
			badText: "Please complete this field",
			tipText: "Here, just input something",
			validateText: function(inputValue, callback) {
				// Checking if the input field contains text.
				if (inputValue.length > 0) callback(1);
				else callback(0);
			},
			validateInRealTime: false
			});
		}					  		
	);
	$("#email").inputTip({
                goodText: "Validated",
                badText: "Email address incorrect",
                tipText: "Type an email address",               
                validateText: function(inputValue, callback) {
                // Checking if the input field contains text.
                    var emailRegexp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                    if (emailRegexp.test(inputValue)) callback(1);
                    else callback(0);
                },
                // True if the validation should be performed on every key/up event (false by default)
                validateInRealTime: false
     });
	
}

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);


function makeTall() { $(this).find("ul.subnav").slideDown('fast').show();}
function makeShort(){ $(this).find("ul.subnav").slideUp('normal');}

jQuery.fn.defuscate = function( settings ) {
    settings = jQuery.extend({
        link: true,
        find: /\b([A-Z0-9._%-]+)\([^)]+\)((?:[A-Z0-9-]+\.)+[A-Z]{2,6})\b/gi,
        replace: '$1@$2'
    }, settings);
    return this.each(function() {
        if ( $(this).is('a[@href]') ) {
            $(this).attr('href', $(this).attr('href').replace(settings.find, settings.replace));
            var is_link = true;
        }
        $(this).html($(this).html().replace(settings.find, (settings.link && !is_link ? '<a href="mailto:' + settings.replace + '">' + settings.replace + '</a>' : settings.replace)));
    });
}

/*
 * 	 imBannerRotater - a JQuery Plugin
 * 	 @author Les Green
 * 	 Copyright (C) 2009 Intriguing Minds, Inc.
 *   Version 0.5
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.

 *   Demo and Documentation can be found at:   
 *   http://www.grasshopperpebbles.com
 *   
 */
 
;(function($) {
	$.fn.extend({
        imBannerRotater: function(options) { 
        	opts = $.extend({}, $.bannerRotater.defaults, options);
			return this.each(function() {
				new $.bannerRotater(this, opts);
			});
        }
    });	

$.bannerRotater = function(obj, opts) {
	var $this = $(obj);
	var imgCnt = 0;
	var ttlImg = 0;
	if (opts.image_url) {
		var d = getDataString();
		doAjax('GET', opts.image_url, d, '', doCreate);
	} else {
		doCreate(opts.images);
	}
	
	function getDataString() {
		var str = '';
		$.each(opts.data, function(i, itm) {
			str += itm.name + "=" + itm.value + "&";							
		});
		//remove last "&"
		str = str.substr(0, (str.length-1));
		return str;
	};
		
	function doAjax(t, u, d, fnBefore, fnSuccess) {
		var dt = (opts.return_type == 'json') ? 'json' : 'text';
		$.ajax({
			type: t,
			url: u,
			data: d,
			dataType: dt,
			beforeSend: fnBefore, //function(){$("#loading").show("fast");}, //show loading just when link is clicked
			//complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
			success: fnSuccess,
			error: showError
	 	}); //close $.ajax(
	};
	
	function showError(XMLHttpRequest, textStatus, errorThrown) {
		console.log(textStatus);
	};
	
	function doCreate(data) {
		//var tbl, tr;
		var img, pic;
		if (opts.return_type == 'list') {
			var daAR = data.split(',');
		} else {
			var daAR = new Array();
			$.each(data, function(i, itm) {
				if (opts.mode == 'random') {
					if (opts.data_map.url_name) {
						daAR[i] = new Array(itm[opts.data_map.image_name], itm[opts.data_map.url_name]);
					} else {
						daAR[i] = itm[opts.data_map.image_name];
					}	
				} else {
					daAR[i] = itm[opts.data_map.image_name];
				}	
			});
		}
		if (opts.mode == 'random') {
			img = new Image();
			if (opts.data_map.url_name) {
				var tgt = (opts.data_map.url_target) ? opts.data_map.url_target : '_blank';
				var sel = daAR[Math.floor(Math.random()*daAR.length)];
				pic = opts.base_path + sel[0];
				var url = sel[1];
				$this.append($('<a></a>').attr({'href': url, 'target': tgt}).append($(img).attr({ src: pic, alt: pic})));
			} else {			
				pic = pickImage(daAR);
				$this.append(pic);
			}	
		} else {
			ttlImg = daAR.length;
			for (var i = 0; i < ttlImg; i++) {
				pic = opts.base_path + daAR[i];
				img = new Image();
				$this.append($(img).attr({ src: pic, alt: pic}).css('display', 'none'));
			}
			imgFadeIn();
		}
	};
	
	function pickImage(daAR){
		img = new Image();
		var index = Math.floor(Math.random()*daAR.length);
		var pic = opts.base_path + daAR[index];
		while($('#'+index).length == 1){
			index = Math.floor(Math.random()*daAR.length);
			pic = opts.base_path + daAR[index];
			console.log('trying');
		}
		return $(img).attr({ src: pic, id:index, width:163, height:103, alt: pic});
	}
	
	function imgFadeIn() {
		$("img:hidden:eq("+imgCnt+")", $this).fadeIn(opts.speed, function(){
			imgFadeOut();
		});
	};
	
	function imgFadeOut() {
		$("img:eq("+imgCnt+")", $this).fadeOut(opts.speed, function(){
			imgCnt = (imgCnt == ttlImg-1) ? 0 : imgCnt + 1;
			imgFadeIn();
		});
	};
};

$.bannerRotater.defaults = {
	mode: 'random',//rotate
	image_url: '',
	data: '',
	images: '',//can be used instead of image_url. contains comma delimited list of images
	return_type: 'list', //list, json
	base_path: '',
	data_map: '', //{image_name: '', url_name: '', url_target: '_blank'}
	speed: 1500
};
})(jQuery);		   