$(function(){
	
	hideFormText();
	initLightbox();
	mainNav();
	subNav();
	initTabs();
	hoverCables();
	smoothScroll();
	popupLoaders();
	submitAjax();
	inputMasked();
	bioDetail();
	newsletterSingup();
	clearFormFields();
	
	$(".overlay").colorbox({opacity:0.7});
	
	$(".index .grid .row div.row:last, .index .grid div.row:last ").addClass("last");
	
	if (!jQuery.browser.mobile) {
		$().UItoTop({ easingType: 'easeOutQuart' });
	}
	
	$(".toValidate").validate();
	
	$("#blog form#comments").validate();
	
	$(".product-list .product:even").addClass("dark");
	
	submitAjax();
	
	$("select#industry-products").change(function(){
		if ($(this).find("option:selected").val()!="") {
			$.colorbox({
				href:"/products/view/" + $(this).find('option:selected').attr('value'),
				opacity: 0.7
			});
		}
	});
	
		
	// Preload images
	$.preload('/images/global-nav-hover.png');
	
	$(".drop-down .button").click(function(){
		$(this).find("+ .drop-down-holder").slideToggle();
	});
	
});

/* mainNav */

function mainNav() {
	$("ul#nav li > a").filter(":has('+ div.drop')").toggle(function() {
		var el = $(this);
		var _parent = $(this).parent('li');		
		var _drop = $("+ .drop", this);
		var bWidth = $('body').width();
		var bHeight = $('#container').outerHeight();
		
		if ($(window).height() > bHeight) bHeight = $(window).height();
		
		if ($("ul#nav li").is(".home")) {
			$("ul#nav .drop").css({"width": 590});
		}
		_drop.fadeIn();
		_parent.css({zIndex: 20, height: _parent.height() + 10 });
		if (_parent.index() > 0) _drop.css({marginLeft: -120 * _parent.index()});
		el.css({bottom: 15});
		$('body').append('<div class="faderNav"></div>');
		$('.faderNav').css({
			position: 'absolute',
			top: 0,
			left: 0,
			width: bWidth,
			height: bHeight,
			background: 'black',
			opacity: 0.7,
			zIndex: 15,
			display: 'none'
		}).fadeIn(300);
		
		$(".faderNav").click(function(){
			el.click();
		});
	},
	function() {
		var _parent = $(this).parent('li');
		var el = $(this);
		var _drop = $("+ .drop", this);
		
		_drop.fadeOut();
		el.css({bottom: 5});
		_parent.css({zIndex: 1, height: _parent.height() - 10 });
		$('.faderNav').fadeOut(300, function() {
			$(this).remove();
		});
	});
	
}

/* subNav */

function subNav() {
	$("ul#nav .drop .holder li > a").hover(
	function(){
		var _index = $(this).parent("li").index();		
		$(this).parentsUntil(".drop").next(".nav-descriptions").find("div").eq(_index).fadeIn();
	}, 
	function(){
		var _index = $(this).parent("li").index();
		$(this).parentsUntil(".drop").next(".nav-descriptions").find("div").eq(_index).hide();
	});
}

/* tabs */

function initTabs() {
	$(".tab-content > div").not(".active").hide();
	$("ul.tab-set li a").click(function(event){
		$("ul.tab-set li a").removeClass("active");
		
		// prevent from scrolling to element
		event.preventDefault();
		var el = $(this);
		var _tab = this.hash;
		
		el.addClass("active");
		$(".tab-content > div").removeClass("active").hide();
		$(_tab).addClass("active").fadeIn();
	});

}

function popupLoaders() {
	$(".product-list a[href='#product-details']").click(function(){
		$("#product-detail-loader").load("/products/view/" + $(this).attr("id"));
	});
	
	$("a[href='#contact-us']").click(function(){
		$.colorbox({
			href:"/contact-us",
			opacity: 0.7,
			scrolling: false,
			onComplete: function () {
				submitAjax();
				clearFormFields();
				inputMasked();
				_gaq.push(['_trackPageview', "/contact/"]);
				clicky.log("/contact/");
				clicky.goal('2865');
			}
		});
	});
	
	$("a[href='#email-us']").click(function(){
		$.colorbox({
			href:"/contact-us",
			opacity: 0.7,
			scrolling: false,
			onComplete: function () {
				submitAjax();
				clearFormFields();
				inputMasked();
				_gaq.push(['_trackPageview', "/email-us/"]);
				clicky.log("/email-us/");
				$("#form-contact-us-popup").attr("name", "form-email-us-popup")
			}
		});
	});
	
	$("a[href='#support-ticket']").click(function(){
		$.colorbox({
			href:"/support-ticket",
			opacity: 0.7,
			scrolling: false,
			onComplete: function () {
				submitAjax();
			}
		});
	});
	
	$("a[href='#product-reg']").click(function(){
		$.colorbox({
			href:"/product-registration",
			opacity: 0.7,
			scrolling: false,
			onComplete: function () {
				submitAjax("<h2 class='blue'>Thank you for registering your product.</h2><h6>If you need to obtain a warranty claim from, please send an email to <a href='mailto:warranty@innovolt.com'>warranty@innovolt.com</a></h6>");
				productRegistration();
				removeRegistration();
			}
		});
	});
}


function bioDetail() {
	$("#about-us .people").hover(
	  function () {
		$(this).find("img").stop(true, true).toggle();
		$(this).find("div.bio").stop(true, true).toggle("slide", {direction: 'right'});
		//$("#about-us #twocolumns").css({paddingBottom: $(this).find("div.bio").height()});
	  }, 
	  function () {
		$(this).find("img").stop(true, true).toggle();
		$(this).find("div.bio").stop(true, true).toggle();
		//$("#about-us #twocolumns").css({paddingBottom: 100});
	  }
	);
}

function inputMasked() {
	$("input.phone").mask("(999) 999-9999");
}

/* hideFormText */
function hideFormText() {
	var _inputs = document.getElementsByTagName('input');
	var _txt = document.getElementsByTagName('textarea');
	var _value = [];
	
	if (_inputs) {
		for(var i=0; i<_inputs.length; i++) {
			if (_inputs[i].type == 'text' || _inputs[i].type == 'password') {
				
				_inputs[i].index = i;
				_value[i] = _inputs[i].value;
				
				_inputs[i].onfocus = function(){
					if (this.value == _value[this.index])
						this.value = '';
				}
				_inputs[i].onblur = function(){
					if (this.value == '')
						this.value = _value[this.index];
				}
			}
		}
	}
	if (_txt) {
		for(var i=0; i<_txt.length; i++) {
			_txt[i].index = i;
			_value['txt'+i] = _txt[i].value;
			
			_txt[i].onfocus = function(){
				if (this.value == _value['txt'+this.index])
					this.value = '';
			}
			_txt[i].onblur = function(){
				if (this.value == '')
					this.value = _value['txt'+this.index];
			}
		}
	}
}

// hoverCables

function hoverCables() {

	$(".hovers h6").toggle(
	function() {
		/*$(".hovers .desc").hide();*/
		if ($(".hovers h6 > a").not($(this)).parents(".hovers").hasClass("active")) {
			$(".hovers.active a").click();
		}
		$(".hovers h6 > a").css({zIndex: 10});
		$(this).parents(".hovers").find(".desc").slideToggle();
		$(".hovers h6 > a").not($("a", this)).css({zIndex: 1});
		$(this).parents(".hovers").addClass("active");
		$(this).find("a").html("-");
	},
	function() {
		$(this).parents(".hovers").find(".desc").hide();
		$(this).parents(".hovers").removeClass("active");
		$(this).find("a").html("+");
	});
}


// smoothScoll

function smoothScroll() {

	$("a[href*=#]").not("ul.tab-set li a").click(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
		
			var $target = $(this.hash);
			$target = $target.length && $target || $("[name=' + this.hash.1) +']");
		
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$("html,body").animate({scrollTop: targetOffset}, {duration:1600,easing:"easeOutQuart"});
			return false;
			}
		
		}
		
	});
}

/* equal heights */

function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

/* ajax forms */

function submitAjax(msg) {
	
	$.validator.addMethod("defaultInvalid", function(value, element) {
		if (element.value == element.defaultValue)	{
			return false;
		}
		return true;
	});
		
	$('.toValidate').each(function () {
	    $(this).validate({
			invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					setTimeout("$.colorbox.resize();", 300);
				}
			},
	        submitHandler: function (form) {
	            $(form).ajaxSubmit({
	                beforeSubmit: function (formData, jqForm, options) {
						$(form).find("input, select, textarea").attr("disabled",true);				
						$(form).fadeTo("slow", 0.5);	
					},
					success: function (responseText, statusText, xhr) {
						$(form).fadeTo("slow", 1);
						if (msg) {
							$(form).html(msg);
						}				
						else {
							$(form).html("<h2 class='blue'>Thank you for contacting Innovolt.</h2><h4>A member of our team will be in touch with you shortly.</h4>");
						}
						
						if ($(form).is('[name=form-contact-us-popup]')) {
							clicky.goal('2865');
							clicky.log('/contact/success/');
							_gaq.push(['_trackPageview', '/contact/success/']);
						}
						
						if ($(form).is('[name=form-email-us-popup]')) {
							clicky.goal('3245');
							clicky.log('/email-us/success/');
							_gaq.push(['_trackPageview', '/email-us/success/']);
						}
					}
	            });
	        }
	    });
	});
}

function newsletterSingup() {

   $('form#newsletter').validate({
		submitHandler: function(form) {
			form.submit();
		}
	});
	
}

function clearFormFields() {
	$('input:text:not([readonly], :disabled), textarea:not([readonly], :disabled)').live({
		focus: function() {
			if (this.value == this.defaultValue) {
				this.value = "";
			}                    
		},
		blur: function() {
			if (!this.value.length) {
				this.value = this.defaultValue;
			}
		}
	});
}


function productRegistration() {

	$('#form-product-reg div.date input').datepicker({
			showOn:'focus',
			dateFormat: 'yy-mm-dd',
			minDate: '-5y',
			maxDate: '+0'
	});
	
	$("#form-product-reg div.add-product input").click(function(){
		$("#form-product-reg div.notice").fadeOut();
		var i = $("#form-product-reg fieldset").length - 1;
		var next = $("#form-product-reg fieldset").length + 1;
		if (i < 2) {
			var cloned = $("#form-product-reg fieldset").eq(0).clone();
			cloned.find('input[type=text], select').each(function() {
				name = $(this).attr('name').slice(0, -1);
				id = $(this).attr('id').slice(0, -1);
				$(this).attr('name', name + next);
				$(this).attr('id', id + next);
			});
			cloned.find('label').each(function() {
				name = $(this).attr('for').slice(0, -1);
				$(this).attr('for', name + next);
			});
			cloned.find("div.remove-product").fadeIn();
			cloned.insertAfter($("#form-product-reg fieldset").eq(i));
			$(".hasDatepicker").each(function(){ 
				$(this).removeClass("hasDatepicker").removeAttr("id").datepicker({ 
					dateFormat: 'yy-mm-dd',
					minDate: '-5y',
					maxDate: '+0'
					});
			});
		} else {
			pulsate($("#form-product-reg div.notice"), 3, 1000);
		}
		$.colorbox.resize();
	});
	
}

function removeRegistration() {

	$("#form-product-reg div.remove-product input").live("click", function(){
		$("#form-product-reg div.notice").fadeOut();
		$(this).closest(".product-reg-info").remove();
		$.colorbox.resize();
	});
	
}

function pulsate(elem, times, duration) {
	 for (var i = 0; i < times; i++) {
		$(elem).show().animate({
		opacity: 0
		}, duration / 2);
		$(elem).animate({
		opacity: 1
		}, duration / 2);
	}
	return;
}

// initlightbox

function initLightbox(){
	$('.with-popup').simplebox();
}

(function($) {
	$.fn.simplebox = function(options) { 
		return new Simplebox(this, options); 
	};
	
	function Simplebox(context, options) { this.init(context, options); };
	
	Simplebox.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				duration: 300,
				linkClose: 'a.close, a.btn-close, input.close',
				divFader: 'fader',
				faderColor: 'black',
				opacity: 0.7,
				wrapper: '#wrapper',
				linkPopap: '.link-submit'
			}, options || {});
			this.btn = $(context);
			this.select = $(this.options.wrapper).find('select');
			this.initFader();
			this.btnEvent(this, this.btn);
		},
		btnEvent: function($this, el){
			el.click(function(){
				if ($(this).attr('href')) $this.toPrepare($(this).attr('href'));
				else $this.toPrepare($(this).attr('title'));
				return false;
			});
		},
		calcWinWidth: function(){
			this.winWidth = $('body').width();
			if ($(this.options.wrapper).width() > this.winWidth) this.winWidth = $(this.options.wrapper).width();
		},
		toPrepare: function(obj){
			this.popup = $(obj);
			this.btnClose = this.popup.find(this.options.linkClose);
			this.submitBtn = this.popup.find(this.options.linkPopap);
			
			if ($.browser.msie) this.select.css({visibility: 'hidden'});
			this.calcWinWidth();
			this.winHeight = $(window).height();
			this.winScroll = $(window).scrollTop();
			
			this.popupTop = this.winScroll + (this.winHeight/2) - this.popup.outerHeight(true)/2;
			if (this.popupTop < 0) this.popupTop = 0;
			this.faderHeight = $(this.options.wrapper).outerHeight();
			if ($(window).height() > this.faderHeight) this.faderHeight = $(window).height();
			
			this.popup.css({
				top: this.popupTop,
				left: this.winWidth/2 - this.popup.outerWidth(true)/2
			}).hide();
			this.fader.css({
				width: this.winWidth,
				height: this.faderHeight
			});
			this.initAnimate(this);
			this.initCloseEvent(this, this.btnClose, true);
			this.initCloseEvent(this, this.submitBtn, false);
			this.initCloseEvent(this, this.fader, true);
		},
		initCloseEvent: function($this, el, flag){
			el.live('click', function(){
				$this.popup.fadeOut($this.options.duration, function(){
					$this.popup.css({left: '-9999px'}).show();
					if ($.browser.msie) $this.select.css({visibility: 'visible'});
					$this.submitBtn.unbind('click');
					$this.fader.unbind('click');
					$this.btnClose.unbind('click');
					$(window).unbind('resize');
					if (flag) $this.fader.fadeOut($this.options.duration);
					else {
						if ($this.submitBtn.attr('href')) $this.toPrepare($this.submitBtn.attr('href'));
						else $this.toPrepare($this.submitBtn.attr('title'));
					}
				});
				return false;
			});
		},
		initAnimate:function ($this){
			$this.fader.fadeIn($this.options.duration, function(){
				$this.popup.fadeIn($this.options.duration);
			});
			$(window).resize(function(){
				$this.calcWinWidth();
				$this.popup.animate({
					left: $this.winWidth/2 - $this.popup.outerWidth(true)/2
				}, {queue:false, duration: $this.options.duration});
				$this.fader.css({width: $this.winWidth});
			});
		},
		initFader: function(){
			if ($(this.options.divFader).length > 0) this.fader = $(this.options.divFader);
			else{
				this.fader = $('<div class="'+this.options.divFader+'"></div>');
				$('body').append(this.fader);
				this.fader.css({
					position: 'absolute',
					zIndex: 999,
					left:0,
					top:0,
					background: this.options.faderColor,
					opacity: this.options.opacity
				}).hide();
			}
		}
	}
}(jQuery));

(function(a){jQuery.browser.mobile=/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

( function( $ ){
 $.preload = function(){
  var tmp = [], i = arguments.length;
  // reverse loop run faster
  for( ; i-- ; ) tmp.push( $( '<img />' ).attr( 'src', arguments[ i ]));
 };
})( jQuery );
