var NXA = NXA || {};


jQuery.fn.clog = function(msg) {
	var txt = msg ? msg : "";
	if (this.console && typeof console.log != "undefined") {
		console.log('%o ', this, txt);
	}
	return this;
}

/* =================================================================== */

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

/* =================================================================== */

NXA.moveProductListingPageNav = function() {
	$('ul.nav-tabs').remove().appendTo('#torso h1').addClass('moved');
}

/* =================================================================== */

NXA.multimediaPlayer = function() {
	
	var setupEvents = function() {
		$('.multimedia #productDemo a').click( function(e) {
			e.preventDefault();
			playVideo(e, this);
		});
		
		$('.multimedia div[id^="video"] a').live('click', function(e) {
			e.preventDefault();
			playVideo(e, this);
		});
		
		$('.multimedia #gallery li a').live('click', function(e) {
			e.preventDefault();
			imageGallery.showImage(e);
		});
		
		//flowplayer test
		$('.multimedia #productDemoFlow a').click( function(e) {
			e.preventDefault();
			playVideoFlow(e, this);
		}); 
		
	}
	
	var imageGallery = function(e) {
		var showImage = function(e) {
			var imgSrc = getImageToShow(e.currentTarget);
			var img = $('#galleryImg img').attr('src', imgSrc);
			$(e.currentTarget).closest('ul').find('a').removeClass('selected').end().end().addClass('selected');
		};
		
		var getImageToShow = function(el) {
			return $(el).attr('href');
		};
		
		return {
			showImage : showImage
		}
	}();
	
	var supportsHtmlVideo = function() {
		return !!document.createElement('video').canPlayType;
	};
	
    var supportsHtml5Video = function() {
        var elem = document.createElement('video'),
            bool = !!elem.canPlayType;
        
        if (bool){
            bool = new Boolean(bool);
            bool.ogg = elem.canPlayType('video/ogg; codecs="theora"');
            
            // Workaround required for IE9, which doesn't report video support without audio codec specified.
            // bug 599718 @ msft connect
            var h264 = 'video/mp4; codecs="avc1.42E01E';
            bool.h264 = elem.canPlayType(h264 + '"') || elem.canPlayType(h264 + ', mp4a.40.2"');
            
            bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"');
        }
        return bool;
    };
	
	var playVideo = function(e, targetEl) {
		var videoName = $(targetEl).attr('href');
		var aVideoName = videoName.split('.');
		var aVideoNameTemp = aVideoName.pop();
		videoName = aVideoName.join('');
		var poster = $(targetEl).find('img').attr('src');
		embedVideo(videoName, poster, targetEl);
	};
	
	//flowplayer testing
	var playVideoFlow = function(e, targetEl) {
		var videoName = $(targetEl).attr('href');
		var aVideoName = videoName.split('.');
		var aVideoNameTemp = aVideoName.pop();
		videoName = aVideoName.join('');
		var poster = $(targetEl).find('img').attr('src');
		embedVideoFlow(videoName, poster, targetEl);
		txtBoxClear();
	};
	
	var pausePlayingVideo = function() {
		if (supportsHtmlVideo()) {
			$('video').each( function() {
				$(this)[0].pause();
			});
		}
		$('object').each( function() {
			if ( 'SetVariable' in $(this)[0] ) {
				$(this)[0].SetVariable("player:jsPause", "");
			}
		});
	};
	
	var embedVideo = function(videoName, poster, targetEl){
		var base_url = '';
		var mp4_url = videoName + '.mp4';
		var rand = Math.floor(Math.random()*197441);
		
		//var video = '<video id="avideo" width="640" height="360" poster="' + poster + '" controls autoplay>';
		//video += '<source src="' + videoName + '.mp4" type="video/mp4" />'; 
		//video += '<source src="' + videoName + '.ogv" type="video/ogg" />';
		var video = '<object width="640" height="360" data="' + base_url + '/media/player_flv_maxi.swf?' + rand 
			+ '" type="application/x-shockwave-flash">';
		video += '<param name="movie" value="/media/player_flv_maxi.swf?' + rand + '" />';
		video += '<param name="wmode" value="transparent" />';
		video += '<param name="FlashVars" value="flv=' + base_url + '' + videoName + '.flv&amp;startimage=' 
			+ poster + '&amp;margin=0&amp;autoplay=1&amp;showvolume=1" />';
		video += '<img src="' + poster + '" />';
		video += 'Your browser does not support html5 video or flash, please upgrade and come back again. Thanks.';
		video += '</object>';
		video += '</video>';
	
		/*
		if ($.browser.isphone()) {
			//play full screen mode for iphone/droid
			window.location = mp4_url;
		} 
		else 
		{
		*/
			$(targetEl).closest('div').empty().html(video).show();
	
			// html5 video tag autoplay doesn't work on ipad
			if ($.browser.safari) {
				var thevideo = document.getElementById('avideo');
				thevideo.load();
				thevideo.play();
			}
		//}		
		_gaq.push(['_trackPageview', 'video/' + videoName + '.mp4']);	
		return video;
	};
	
	//flowplayer testing
	var embedVideoFlow = function(videoName, poster, targetEl){
		var base_url = '';
		var mp4_url = videoName + '.mp4';
		var rand = Math.floor(Math.random()*197441);
		
		var video = '<video id="avideo" width="640" height="360" poster="' + poster + '" controls autoplay onended="html5Ended();">';
		video += '<source src="' + videoName + '.mp4" type="video/mp4" />'; 
		video += '<source src="' + videoName + '.ogv" type="video/ogg" />';
		video += '<a href="http://www.nexsan.com' + videoName + '.flv" style="display:block;width:640px;height:360px" id="flowplayerholder"></a>';
		var ua = $.browser;
  		if (ua.msie && $.browser.version >= 9.0){
  			video += '<script> flowplayer("flowplayerholder", "flowplayer-3.2.7.swf", { clip: { autoPlay: false, onFinish : function() { flowEnded(); } } }); </script>';
  		}else{
			video += '<script> flowplayer("flowplayerholder", "flowplayer-3.2.7.swf", { clip: { onFinish : function() { flowEnded(); } } }); </script>';
  		}
		video += '</video>';
		video += '<div id="the_video_form">';
		//video += '<form id="contact_form_short" class="form" action="http://now.eloqua.com/e/f2.aspx">';
		video += '<form id="video_form" class="form" action="http://www.nexsan.com/media/video_thank_you.aspx">';
		video += '<!-- Eloqua fields -->';
        video += '<input type="hidden" name="campaign" value="" id="campaign"/>';
        video += '<input type="hidden" name="source" value="" id="source"/>';
        video += '<input type="hidden" name="source_info" value="" id="source_info"/>';
        video += '<input type="hidden" name="source_type" value="" id="source_type"/>';
        video += '<input type="hidden" name="source_email" value="" id="source_email"/>';
        video += '<input type="hidden" name="source_reseller" value="" id="source_reseller"/>';
        video += '<input type="hidden" name="elqFormName" value="2011ContactUsForm"/>';
		video += '<input type="hidden" name="elqSiteID" value="1220"/>';
		video += '<input type="hidden" name="video" value="' + videoName + '"/>';
        video += '<h2>WANT MORE INFORMATION? COMMENTS ABOUT THIS VIDEO? LET US KNOW.</h2>';
        video += '<div class="row">';
		video += '<label>Name</label>';
        video += '<div><input id=FirstName name="FirstName" class="placeholder" type="text" placeholder="first name" /></div>';
        video += '<div><input id=LastName name="LastName" class="placeholder" type="text" placeholder="last name"/></div>';
        video += '</div>';
		video += '<div class="row">';
        video += '<label>Contact</label>';
		video += '<div><input id=Phone name="Phone" class="placeholder" type="text" placeholder="phone" /></div>';
        video += '<div><input id=EmailAddress name="EmailAddress" class="placeholder" type="email" placeholder="email" /></div>';
        video += '</div>';
        video += '<div class="row">';
        video += '<div><label class="message"> Message</label>';
		video += '<textarea id=CommentsQuestions name="CommentsQuestions" placeholder="Message"></textarea></div>';
        video += '</div>';
        video += '<div class="row button">';
        video += '<input type="submit" name="submit1" value="Submit"  />';
        video += '</div><div class="replay_button_holder"><input type="button" class="replay_button" onclick="replay_video();" value="Replay Video"></div>';
        video += '</form>';
        video += '</div>';
		/*
		if ($.browser.isphone()) {
			//play full screen mode for iphone/droid
			window.location = mp4_url;
		} 
		else 
		{
		*/
			$(targetEl).closest('div').empty().html(video).show();
	
			// html5 video tag autoplay doesn't work on ipad
			if ($.browser.safari) {
				var thevideo = document.getElementById('avideo');
				thevideo.load();
				thevideo.play();
			}
		//}		
		//_gaq.push(['_trackPageview', 'video/' + videoName + '.mp4']);	
		return video;
	};
	
	
	var markSelectedMediaInNav = function(parentSelector, mediaId) {
		$('a[href$="'+ mediaId +'"]', $(parentSelector)).closest('ul').find('a').removeClass('selected').end().end().addClass('selected');
	};
	
	var showSelectedMedia = function(parentSelector, mediaId) {
		$('#'+ mediaId, $(parentSelector)).siblings().removeClass('selected').end().addClass('selected');
	};
	
	
	// using sammy.js to load proper media block section from URL hash
	var sammyApp = function() {		
		var app = $.sammy(function() {
			this.element_selector = '.multimedia';
			
			this.get('#/:id', function(context) {
				pausePlayingVideo();
				markSelectedMediaInNav(this.$element(), context.params.id);
				showSelectedMedia(this.$element(), context.params.id);
			});
		});
		
		$(function() {
			app.run();
		});
	};
	
	var init = function() {
		setupEvents();
		sammyApp();
	};
	
	return {
		init : init,
		sammyApp : sammyApp
	}
}();


/* =================================================================== */


jQuery.validator.addMethod("notEqualFirst", function(value, element, param) {
 return this.optional(element) || value != $(param).val();
}, "Can't match Last");


jQuery.validator.addMethod("notEqualLast", function(value, element, param) {
 return this.optional(element) || value != $(param).val();
}, "Can't match First");

var eloquaForms = function(){
	var email;
	var jQ = jQuery;
	jQ(document).ready(function(){
		jQ("#contact_form_short").validate({
			rules: {
				EmailAddress: {
					email: true,
					required: true
				},
				FirstName: {
					required: true,
					notEqualFirst: "#LastName"
				},
				LastName: {
					required: true,
					notEqualLast: "#FirstName"
				},
				Phone: "required"
			},
			submitHandler: function(element){
				email = jQ("#contact_form_short #EmailAddress").val();
				jQ.getScript('http://now.eloqua.com/visitor/v200/svrGP.aspx?pps=50&siteid=1220&DLKey=d68f60c3bc0449e09451dedebd6d8fc8&DLLookup=%3CC_EmailAddress%3E' + email + '%3C/C_EmailAddress%3E&ms=2', function(){
					if (typeof GetElqContentPersonalizationValue == "function") {
						if (GetElqContentPersonalizationValue('C_EmailAddress') != "") {
						
							location.href = 'http://now.eloqua.com/e/f2.aspx?elqFormName=2011ContactUsFormShort&elqSiteID=1220&EmailAddress=' + jQ("#contact_form_short #EmailAddress").val() + '&FirstName=' + jQ("#contact_form_short #FirstName").val() + '&LastName=' + jQ("#contact_form_short #LastName").val() + '&Phone=' + jQ("#contact_form_short #Phone").val() + '&CommentsQuestions=' + encodeURIComponent(jQ("#contact_form_short #CommentsQuestions").val()) + '&Country=' + GetElqContentPersonalizationValue('C_Country') + '&StateProvince=' + GetElqContentPersonalizationValue('C_State_Prov') + '&ZiporPostalCode=' + GetElqContentPersonalizationValue('C_Zip_Postal') + '&Company=' + GetElqContentPersonalizationValue('C_Company') + '&Howdidyouhear=' + GetElqContentPersonalizationValue('C_How_did_you_hear_1') + '&Industry=' + GetElqContentPersonalizationValue('C_Industry1') + '&ContactType=' + GetElqContentPersonalizationValue('C_Contact_Type1') + '&FormValidation=rzqnz';
						}
						else {
							location.href = 'http://now.eloqua.com/e/f2.aspx?elqFormName=2011ContactUsFormShort&elqSiteID=1220&EmailAddress=' + jQ("#contact_form_short #EmailAddress").val() + '&FirstName=' + jQ("#contact_form_short #FirstName").val() + '&LastName=' + jQ("#contact_form_short #LastName").val() + '&Phone=' + jQ("#contact_form_short #Phone").val() + '&CommentsQuestions=' + encodeURIComponent(jQ("#contact_form_short #CommentsQuestions").val());
						}
					}
					else {
						location.href = 'http://now.eloqua.com/e/f2.aspx?elqFormName=2011ContactUsFormShort&elqSiteID=1220&EmailAddress=' + jQ("#contact_form_short #EmailAddress").val() + '&FirstName=' + jQ("#contact_form_short #FirstName").val() + '&LastName=' + jQ("#contact_form_short #LastName").val() + '&Phone=' + jQ("#contact_form_short #Phone").val() + '&CommentsQuestions=' + encodeURIComponent(jQ("#contact_form_short #CommentsQuestions").val());
					}
				});
			}
		});
	});
};




var videoForms = function(){
	var email;
	var jQ = jQuery;
	jQ(document).ready(function(){
		jQ("#video_form").validate({
			rules: {
				EmailAddress: {
					email: true,
					required: true
				},
				FirstName: "required",
				LastName: "required",
				Phone: "required"
			},
			submitHandler: function(element){
				email = jQ("#video_form #EmailAddress").val();
				jQ.getScript('http://now.eloqua.com/visitor/v200/svrGP.aspx?pps=50&siteid=1220&DLKey=d68f60c3bc0449e09451dedebd6d8fc8&DLLookup=%3CC_EmailAddress%3E' + email + '%3C/C_EmailAddress%3E&ms=2', function(){
					if (typeof GetElqContentPersonalizationValue == "function") {
						if (GetElqContentPersonalizationValue('C_EmailAddress') != "") {
						
							location.href = 'http://now.eloqua.com/e/f2.aspx?elqFormName=2011ContactUsFormShort&elqSiteID=1220&EmailAddress=' + jQ("#video_form #EmailAddress").val() + '&FirstName=' + jQ("#video_form #FirstName").val() + '&LastName=' + jQ("#video_form #LastName").val() + '&Phone=' + jQ("#video_form #Phone").val() + '&CommentsQuestions=' + encodeURIComponent(jQ("#video_form #CommentsQuestions").val()) + '&Country=' + GetElqContentPersonalizationValue('C_Country') + '&StateProvince=' + GetElqContentPersonalizationValue('C_State_Prov') + '&ZiporPostalCode=' + GetElqContentPersonalizationValue('C_Zip_Postal') + '&Company=' + GetElqContentPersonalizationValue('C_Company') + '&Howdidyouhear=' + GetElqContentPersonalizationValue('C_How_did_you_hear_1') + '&Industry=' + GetElqContentPersonalizationValue('C_Industry1') + '&ContactType=' + GetElqContentPersonalizationValue('C_Contact_Type1') + '&FormValidation=rzqnz';
						}
						else {
							location.href = 'http://now.eloqua.com/e/f2.aspx?elqFormName=2011ContactUsFormShort&elqSiteID=1220&EmailAddress=' + jQ("#video_form #EmailAddress").val() + '&FirstName=' + jQ("#video_form #FirstName").val() + '&LastName=' + jQ("#video_form #LastName").val() + '&Phone=' + jQ("#video_form #Phone").val() + '&CommentsQuestions=' + encodeURIComponent(jQ("#video_form #CommentsQuestions").val());
						}
					}
					else {
						location.href = 'http://now.eloqua.com/e/f2.aspx?elqFormName=2011ContactUsFormShort&elqSiteID=1220&EmailAddress=' + jQ("#video_form #EmailAddress").val() + '&FirstName=' + jQ("#video_form #FirstName").val() + '&LastName=' + jQ("#video_form #LastName").val() + '&Phone=' + jQ("#video_form #Phone").val() + '&CommentsQuestions=' + encodeURIComponent(jQ("#video_form #CommentsQuestions").val());
					}
				});
			}
		});
	});
};


/* =================================================================== */

/**
 * checks for support of a given attribute on a given element
 * @param {Object} element
 * @param {Object} attribute
 */
var elementSupportsAttribute = function(element, attribute){
	var test = document.createElement(element);
	if (attribute in test) {
		return true;
	}
	else {
		return false;
	}
}


/* =================================================================== */


/**
 * check for browser support of the placeholder attribute
 * and if no support exists, add support through script
 * @requires elementSupportsAttribute
 */
var txtBoxClear = function() {
	if (!elementSupportsAttribute('input', 'placeholder')) {
		$('input[placeholder], textarea[placeholder]')
	        .focus(function() {
	            var $input = $(this);
	            if ($input.val() == $input.attr('placeholder')) {
	                $input.val('');
	                $input.removeClass('placeholder');
	            }
	        })
	        .blur(function() {
	            var $input = $(this);
	            if ($input.val() == '') {
	                $input.addClass('placeholder');
	                $input.val($input.attr('placeholder'));
	            }
	
	        })
	        //Run once on load
	        .blur();
	
	    // Clear all 'placeholders' on submit
	    $('input[placeholder], textarea[placeholder]').parents('form').submit(function() {
	        $(this).find('[placeholder]').each(function() {
	            var $input = $(this);
	            if ($input.val() == $input.attr('placeholder')) {
	                $input.val('');
	            }
	        });
	    });
	}
}


/* =================================================================== */

// function: supermenus
// desc: functionality for the main nav menus
var supermenus = function(){
	var sNavId = 'nav';
	var sMenuClass = 'menu';
	var timerOpen, timerClose;
	

	var setUpEvents = function() {	
	
		$('#'+sNavId + ' a').mouseenter( function(e) {
			if (timerClose) {
				killTimer(timerClose);
			}
			hideAllMenus();
			var current = this;
			// if we're coming FROM a nav item OR a menu, open menu right away
			if ( isRelatedTargetNav(e) || isRelatedTargetMenu(e) ) {
				showMenu(current);
			} else {
				timerOpen = window.setTimeout(function() {
					showMenu(current);
				}, 250);
			}
			
		}).mouseleave( function(e) {
			// if we mouse out of the nav item, kill the timer
			if (timerOpen) {
				killTimer(timerOpen);
			}
			// if mousing onto a menu, keep it visible. 
			// if mousing somewhere else, hide the menu
			if ( !isRelatedTargetMenu(e) ) {
				hideMenu( $(this) );
			}
		});
		
		// leave the menu
		$('.'+sMenuClass).mouseleave( function(e) {
			// if you mouse back onto a nav item
			if ( isRelatedTargetNav(e) ) {
				hideAllMenus();
			} else {
				// else close all menus
				timerClose = setTimeout(function() {
					hideAllMenus();
				}, 500);
			}
		}).mouseenter( function(e) {
			if (timerClose) {
				killTimer(timerClose);
			}
		});
		
	};
	
	var isRelatedTargetNav = function(e) {
		if ( $(e.relatedTarget).closest('#' + sNavId).length != 0) {
			return true;
		}
		return false;
	};
	
	var isRelatedTargetMenu = function(e) {
		if ( $(e.relatedTarget).closest('.' + sMenuClass).length != 0) {
			return true;
		}
		return false;
	};
	
	var showMenu = function(el) {
		$parentLi = $(el).parent('li');
		$parentLi.addClass('hover');
		var menuName = $parentLi.attr("id");
		$('#'+menuName+'-menu').show();
	};
	
	var hideMenu = function(el) {
		$parentLi = $(el).parent('li');
		$parentLi.removeClass('hover');
		var menuName = $parentLi.attr("id");
		$('#'+menuName+'-menu').hide();
	};
	
	var hideAllMenus = function()	{
		$('.'+sMenuClass).hide();
		$('#'+sNavId + ' li').removeClass('hover');
	};	
	
	var killTimer = function(timer) {
		if (typeof timer != "undefined") {
			clearTimeout(timer);
		}
	};
	
	return {
		init : setUpEvents
	}
	
	
}();

/* =================================================================== */

//homepage accordian functionality in focus area

NXA.accordianContent = function() {
	$('.focus .focusContent').not(':first').hide();
	$('.focus .focusContent:first').slideDown();
	
	$('.focus a.title').click( function(e) {
		e.preventDefault();
		var $this = $(this);
		if ( $this.next('.focusContent').is(':hidden') ) {
			$('.focus .focusContent').slideUp();
			$(".focus a").removeClass('selected');
			$this.next('.focusContent').slideDown();
			$this.addClass('selected');
		}
	});
};



/* =================================================================== */

//Leadership functionality

NXA.leadershipContent = function() {
	$('li.selected div.desc').show();
	
	
	$('.prodName').click( function(e) {
		e.preventDefault();
		var $this = $(this);
		if ( $this.next('div.desc').is(':hidden') ) {
			$('.leadership li div.desc').hide();
			$(".leadership li").removeClass('selected');
			$this.next('div.desc').show();
			$this.parent().addClass('selected');
		}
	});
};

/* =================================================================== */

//expand/collapse functionality on videos page
NXA.expandCollapse = function() {
	$('.moreVideos').hide();
		
	$('.viewMore a').toggle( function(e) {
		e.preventDefault();
			$(this).parent().parent().next('.moreVideos').slideDown();
		}, function() {
			$(this).parent().parent().next('.moreVideos').slideUp();	
	});
};


/* =================================================================== */


NXA.anchors = function() {
	addBehaviors = function() {
		$('a').live('click', function(e) {
			if($(this).href.charAt(0) != '#'){
				if (
					$(this).attr('rel') == 'external' || 
					$(this).hasClass('external') || 
					$(this).hasClass('pdf') || 
					$(this).hasClass('popupFull') || 
					this.href.indexOf(location.hostname) == -1
					) {
					// external links
					e.preventDefault();
					return openWin(this,"");
				} else if ($(this).hasClass('popup')) {
					// popup
					e.preventDefault();
					return openWin(this,"height=550,width=600,scrollbars=yes");
				}
			}
		});
	};
	
	openWin = function(o,params) {
		if(params == ""){
			window.open(o.href);
		}else{
			window.open(o.href, "newwin","" + params + "");
		}
		return false;
	};
	
	return {
		addBehaviors : addBehaviors
	}
}();


/* =================================================================== */

$(document).ready(function() {
	txtBoxClear();
	Cufon.replace('#torso h1'); 
	Cufon.replace('.SiteSectionLandingPage .colContent h3');
	supermenus.init();
	eloquaForms();
	NXA.accordianContent();
	NXA.multimediaPlayer.init();
	NXA.anchors.addBehaviors();
});

/* ================================ Dystrick Added =================================== */

$(document).ready(function() {
	$(".podcasts").fancybox();
//	$('.multimedia ul#mediaNav.fourBoxes li a').vAlign();
});

//(function ($) {
// VERTICALLY ALIGN FUNCTION
//$.fn.vAlign = function() {
//	return this.each(function(i){
//	var ah = $(this).height();
//	var ph = $(this).parent().height();
//	var mh = (ph - ah) / 2;
//	$(this).css('padding-top', mh);
//	});
//};
//})(jQuery);

