﻿/* Javascript stylesheet */
document.write("<link rel=\"StyleSheet\" href=\"/spirentAssets/css/spirentJs.css\" type=\"text/css\" media=\"screen\" />");

$(document).ready(function() {

    fnCustomForms();
    fnButtonHovers();
    fnLoadForms();
    fnMiniFlyout();
    fnStateDropdown();

    // Tabs
    $(function() {
	var tabContainers = $('div.tabs > div');

	$('div.tabs ul.tabNavigation a').click(function() {
	    $('div.tabs > div').addClass('hidden');
	    $('div.tabs > div').removeClass('shown');
	    tabContainers.filter(this.hash).removeClass('hidden');
	    tabContainers.filter(this.hash).addClass('shown');

	    $('div.tabs ul.tabNavigation li').removeClass('active');
	    $(this).parent().addClass('active');

	    return false;
	});
    });

    $('h2.tab-title').hide();



    var getXY = function(k) {
	var l = [0, 0];
	do {
	    l[0] += k.offsetLeft;
	    l[1] += k.offsetTop;
	} while (k = k.offsetParent);
	return l;
    };



    // IE6 Flyout Nav
    if ('ActiveXObject' in window && !('XMLHttpRequest' in window)) {

	try {
	    document.execCommand("BackgroundImageCache", false, true);
	} catch(err){}

	var shim = document.createElement('iframe');
	shim.style.border = '0';
	//shim.src = '/';
	shim.setAttribute('frameBorder', '0');
	shim.frameborder = '0';
	shim.border = '0';
	shim.style.position = 'absolute';
	shim.style.top = '0';
	shim.style.left = '0';
	shim.style.visibility = 'hidden';
	document.body.appendChild(shim);
	$(function() {
	    $('#nav1 , #nav2 , #nav3 , #nav4 , #nav5').hover(function() {
		$(this).addClass('hover');
		var flyout = this.getElementsByTagName('div')[0];
		if (flyout){
		    var coords = getXY(flyout);
		    var flyoutDims = [flyout.offsetWidth, flyout.offsetHeight];
		    shim.style.width = flyoutDims[0] + 'px';
		    shim.style.height = flyoutDims[1] + 'px';
		    shim.style.left = coords[0] + 'px';
		    shim.style.top = coords[1] + 'px';
		    shim.style.visibility = '';
		}

	    }, function() {
		$(this).removeClass('hover');
		shim.style.visibility = 'hidden';
	    });
	});



	$(function() {
	    $('#share-bar').hover(function() {
		$(this).addClass('hover');
	    }, function() {
		$(this).removeClass('hover');
	    });
	});
    };


    // init Youtube player
    youTubeLinks();
    videoLinks();
    videoEmbed();

});

function fnButtonHovers(){

    $(':image.hov').unbind('mouseenter mouseleave').hover(
	function(){
	    var src = $(this).attr('src');
	    src =  src.replace('-on', ''); //deal with sticking buttons
	    src =  src.replace('.gif', '-on.gif');
	    $(this).attr('src', src);
	},function(){
	    var src = $(this).attr('src');
	    src =  src.replace('-on', '');
	    $(this).attr('src', src);
	});
}


function assignForm(prefix, qString) {

    $('a.' + prefix).click(function() {
	//reset form in case it has already been used
	$("#form")[0].reset();
	if ( $("#submitButtonWrapper").length > 0 ) {
	    $('#submitButtonWrapper').show();
	}
	if ( $("#formWrapper").length > 0 ) {
	    $('#formWrapper').show();
	}
	if ( $("#messages").length > 0 ) {
	    $('#messages').html('');
	}

	var uId = getVar($(this).attr('href'), qString);


	$('#' + prefix + 'Id').attr('value', uId);

	$.blockUI.defaults.css = {};
	$.blockUI({
	    message: $('#' + prefix + 'Form')
	});
	/*$('#'+prefix+'SubmitBtn').unbind('click').click(function(){
        //alert('validate and send ' +prefix);
        //do validation
        // if validation ok send form
        //return false;
        });*/



	$('a.close, a.cancel').unbind('click').click(function() {
	    $.unblockUI();
	    $('.validation ul li').remove();
	    return false;
	});
	fnButtonHovers();
	return false;
    });
}

function assignFormWP(prefix, qString) {

    $('a.' + prefix).click(function() {

	var uId = $(this).attr('href');/*getVarWP($(this).attr('href'), qString);*/

	$('.whitepaperId').attr('value', uId);
	$.blockUI.defaults.css = {};
	$.blockUI({
	    message: $('#' + prefix + 'Form')
	});

	$('#downloadForm').show();
	$('#messagesWP').html("").hide();

	/*$('#'+prefix+'SubmitBtn').unbind('click').click(function(){
        //alert('validate and send ' +prefix);
        //do validation
        // if validation ok send form
        //return false;
        });*/

	//if the link exists submit the form
	if($('#content_0_DownloadLink').length){
	    $('#whitepaperForm form').submit();
	}

	$('a.close, a.cancel').unbind('click').click(function() {
	    $.unblockUI();
	    $('.validation ul li').remove();
	    return false;
	});
	fnButtonHovers();
	return false;
    });
}


//contact form overlay function
function assignFormCF(prefix, qString) {

    $('a.' + prefix).click(function() {

	//var uId = $(this).attr('href');/*getVarWP($(this).attr('href'), qString);*/

	//$('.whitepaperId').attr('value', uId);
	$.blockUI.defaults.css = {};
	$.blockUI({
	    message: $('#' + prefix + 'Form')
	});

	$('#' + prefix + 'Form') .show();
	//$('#messagesWP').html("").hide();

	/*$('#'+prefix+'SubmitBtn').unbind('click').click(function(){
        //alert('validate and send ' +prefix);
        //do validation
        // if validation ok send form
        //return false;
        });*/

	//if the link exists submit the form
	//if($('#content_0_DownloadLink').length){
	//    $('#whitepaperForm form').submit();
	//}

	$('a.close, a.cancel').unbind('click').click(function() {
	    $.unblockUI();
	    $('.validation ul li').remove();
	    return false;
	});
	//fnButtonHovers();
	return false;
    });
}


function fnLoadForms(){
    $('body').append('<div id="whitepaperForm"></div>');
    $('body').append('<div id="eventForm"></div>');
    $('body').append('<div id="sendForm"></div>');
    $('body').append('<div id="test2"><div id="emailSpirentForm"></div></div>');
    $('#whitepaperForm, #eventForm, #sendForm, #emailSpirentForm').hide();

    /*
    if($('a.event').length>0){
        $('#eventForm').load('eventForm.html',null,function(data, status){
            if(status == 'success'){
                //assignEventForm();
                assignForm('event', 'id');
                $('form', this).validate({
                    errorLabelContainer: $('.validation ul', this),
                    wrapper: "li",
                    submitHandler: function(form) {
                       //AJAX SUBMIT GOES HERE;
                        alert('event form is valid');
                       return false;
                       }
                 });

            }
        });
    }
    */

    /*
    $('#eventForm').load('eventForm.html',null,function(data, status){
        if(status == 'success'){
            //assignEventForm();
            assignForm('event', 'id');
            $('form', this).validate({
                errorLabelContainer: $('.validation ul', this),
                wrapper: "li",
                submitHandler: function(form) {
                   //AJAX SUBMIT GOES HERE;
                    alert('event form is valid');
                   return false;
                   }
             });

        }
    });
    */


    if($('a.send').length>0){
	$('#sendForm').load('/send-to-friend-popup.aspx',null,function(data, status){
	    if(status == 'success'){
		//assignEventForm();
		assignForm('send', 'url');
		$('form', this).validate({
		    errorLabelContainer: $('.validation ul', this),
		    wrapper: "li",
		    submitHandler: function(form) {
			//AJAX SUBMIT GOES HERE;
			var sSendTo = $("#sendTo").val();
			var sSendFrom = $("#sendFrom").val();
			var sSendComments = $("#sendComments").val();
			var sSendUrl = $("#sendId").val();
			//$.post("send-to-friend-popup.aspx", { to: sendTo, from: SendFrom, comments: sendComments, url: sendUrl, ajax: "true"} );
			$.getJSON("/send-to-friend-popup.aspx", {
			    sendTo: sSendTo,
			    sendFrom: sSendFrom,
			    sendComments: sSendComments,
			    url: sSendUrl,
			    ajax: "true"
			}, function(json){
			    if(json.status == "true"){
				//$.unblockUI();
				$('#formWrapper').hide();
				$('#submitButtonWrapper').hide();
				$('#messages').html('<p>' + json.alerts[0] + '</p>');
			    }
			    else{
				var sAlertMessages = "";
				sAlertMessages = "<ul>";
				for(i=0; i < json.alerts.length;i++){
				    sAlertMessages = "<li>" + sAlertMessages + json.alerts[i] + "</li>";
				}
				sAlertMessages =  sAlertMessages + "</ul>";
				$('#validation').html('<p>' + json.alerts[0] + '</p>');
			    }
			});

			return false;
		    }
		});

	    }
	});


    }


    if ($('a.whitepaper').length > 0) {
	$('#whitepaperForm').load('/white-paper-form.aspx', null, function(data, status) {
	    if (status == 'success') {
		//assignWhitePaperForm();
		assignFormWP('whitepaper', 'id');
		fnStateDropdown();
		$('form', this).validate({
		    errorLabelContainer: $('.validation ul', this),
		    wrapper: "li",
		    submitHandler: function(form) {
			//var uId = getVarWP($(this).attr('href'), 'id');
			var uId = $('.whitepaperId').val();
			//AJAX SUBMIT GOES HERE;
			//var detailTitle = $(".whitepaperFormTitle").val();
			var detailFirstname = $(".whitepaperFormFirstName").val();
			var detailSurname = $(".whitepaperFormSurname").val();
			var detailsCompany = $(".whitepaperFormCompany").val();
			var detailsEmail = escape($(".whitepaperFormEmail").val());
			var detailsPhone = escape($(".whitepaperFormPhone").val());
			var detailsCountry = $(".whitepaperFormCountry").val();
			var country = document.getElementById('content_0_country');
			var countryName = country.options[country.selectedIndex].text.toLowerCase();
			var detailsState = $('#whitepaperForm #form .whitepaperFormState').val();//$(".whitepaperFormState").val();
			var detailsNewsletter = $(".whitepaperFormNewsletter input").val();
			var stateErrorMessage = $('#whitepaperForm #form .validation ul').html().toString();

			if(validateCountryStateWP(detailsState,countryName)){
			    $('#whitepaperForm #form #content_0_valSummary').html("");
			    $.ajax({
				type: "GET",
				url: "/white-paper-form.aspx",
				beforeSend: function(xhr) {
				    $('#wpLoading').show();
				},
				data: {
				    //title: detailTitle,
				    firstname: detailFirstname,
				    surname: detailSurname,
				    company: detailsCompany,
				    email: detailsEmail,
				    phone: detailsPhone,
				    country: detailsCountry,
				    state: detailsState,
				    newsletter: detailsNewsletter,
				    whitepaperId: uId,
				    ajax: "true"
				},
				success: function(msg){
				    //$("#whitepaperForm .overlayForm").html(msg);
				    $('#wpLoading').hide();
				    $('#downloadForm').hide();
				    $('#submitButtonWrapperWP').hide();
				    $('#messagesWP2').html("").hide();
				    $('#messagesWP').html(msg).show();
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
				    alert(textStatus);
				}
			    });
			}else if(stateErrorMessage.indexOf("State")==-1)
			{
			    $('#whitepaperForm #form .validation ul').append("<li>State</li>");
			    $('#whitepaperForm #form .validation ul').show();
			    $('#whitepaperForm #form #content_0_valSummary').html("");
			//return;
			}
			return false;
		    }
		});
	    }
	});
    }

    contactOverlaySetup();

    $('a.emailSpirent').click(function(){
	contactOverlaySetup();
    });



}

function validateCountryStateWP(state,countryName)
{
    var isValid=true;

    if(countryName=="usa" || countryName=="canada")
    {
	if(state=='' || state==null)
	    isValid=false;
    }

    return isValid;

}

function contactOverlaySetup()
{

    //code for overlay related to contact form
    var link = $('a.emailSpirent').attr('href');
    var section=getParameterByName(link,'section');
    var referurl=getParameterByName(link,'referurl');
    var rb=getParameterByName(link,'rb');
    //alert(rb);
    if ($('a.emailSpirent').length > 0) {
	$('#emailSpirentForm').load('/contact-form.aspx?section='+section+'&referurl='+referurl, null, function(data, status) {
	    if (status == 'success') {
		assignFormCF('emailSpirent', 'id');
		$('#emailSpirentForm .close').click(function() {
		    $.unblockUI();
		});
		$('#main .close').unbind('click').click(function() {
		    $.unblockUI();

		    return false;
		});
		$('form', this).validate({
		    errorLabelContainer: $('.validation ul', this),
		    wrapper: "li",
		    submitHandler: function(form) {

			var validation='';

			//AJAX SUBMIT GOES HERE;
			var title=$('.ddtitle option:selected').text();
			validation=validateVariable('Title',title, validation);

			var forename=$(".txforename").val();
			validation=validateVariable('First Name',forename, validation);

			var surname=$(".txsurname").val();
			validation=validateVariable('Last Name',surname, validation);

			var company=$(".txcompany").val();
			validation=validateVariable('Company',company, validation);

			//var country=$("#content_2_country");
			//var countryName;//=country.options[country.selectedIndex].text.toLowerCase();

			var country = document.getElementById('content_2_country');
			var countryName = country.options[country.selectedIndex].text.toLowerCase();
			var countryValue=$('.emailForm #content_2_country option:selected').val();

			try{
			    //var tmp=$('#state option:selected')[1];
				var state=$('.emailForm .state-ddl #state option:selected').val();

			}
			catch(err){
			    var state='';
			}
			validation=validateStateVariable('State',countryName,state,validation);

			var email=$(".txemail").val();
			validation=validateVariable('Email address',email, validation);
			validation=validateEmail('Invalid email address',email,validation);

			var phone=$(".txphone").val();
			validation=validateVariable('Telephone',phone, validation);

			var chphone=$('.chphone input').is(':checked')
			var information=$(".txinformation").val();

			if(validation!="")
			{
			    //alert(validation);
			    validation = "Please check the following fields:<p style='color:red;'>"+validation+"</p>";
			    $('#content_2_valSummary').html(validation+'<br/>');
			    $('#content_2_valSummary').show();
			    return false;
			}
			else
			{
			    $.ajax({
				type: "GET",
				url: '/contact-form.aspx',
				data: {
				    section: section,
				    referurl: referurl,
				    rb:rb,
				    title:title,
				    forename:forename,
				    surname: surname,
				    company: company,
				    country: countryName,
					countryId: countryValue,
				    state: state,
				    email:email,
				    phone: phone,
				    chphone:chphone,
				    information: information
				},
				success: function(msg){

				    $('#emailSpirentForm').html(msg);
				    $('#form h1').html('THANK YOU FOR YOUR ENQUIRY');
				    $('a.close, a.cancel').unbind('click').click(function() {
					$.unblockUI();
					$('#emailSpirentForm .overlayForm').hide();
					$('.blockMsg').hide()
					$('.validation ul li').remove();
					return false;
				    });
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
				    alert(textStatus);
				}
			    });
			}
			return false;
		    }
		});
	    }
	});
    }
//end code
}

function validateVariable(name,variable, validation)
{
    if(variable==null || variable==''){
	validation+=name+'<br />';
	return validation;
    }else
	return validation;
}

function validateEmail(name,variable,validation)
{
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailReg.test(variable))
    {
	validation+=name+'<br />';
	return validation;
    }
    else
    {
	return validation;
    }
}

function validateStateVariable(name,country,state,validation)
{
    //alert(country +' - '+state);
    if (country == "usa" || country == "canada") {
	if(state==null || state=='')
	{
	    validation+=name+'<br />';
	    return validation;
	}
	else{
	    return validation;
	}
    }
    else if(country=='please select' || country==null)
    {
	validation+='Country<br />';
	return validation;
    }
    // else if(state=='' || stete==null && (country == "usa" || country == "canada"))
    // {
    // validation+='State<br />';
    // return validation;
    // }
    else
	return validation;
}


function getParameterByName(url,name)
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if(results == null)
	return "";
    else
	return decodeURIComponent(results[1].replace(/\+/g, " "));
}


function fnStateDropdown(){
    $('.state-ddl').hide();

    $country = $('select.country');

    function fnCountryChange($obj){
	var txt = $(':selected', $obj).text().toLowerCase();
	var $targ = $obj.parent().next('.state-ddl');

	if(txt=="usa" || txt=="canada"){
	    $targ.fadeIn();
	}else{
	    $targ.fadeOut();
	}
    }

    $country.change(function(){
	fnCountryChange($(this));
    });

    fnCountryChange($country);

}

function getVar(idString, qString){
    var idArr = idString.split('?');
    var uId = idArr[1].replace(qString + '=', '');

    return uId;
}

function getVarWP(idString, qString) {
    var uId = idString.replace(qString + '=', '');
    //  alert(uId);

    return uId;

}

function videoLinks() {
    $('body').append('<style type="text/css">div.blockMsg #video_window a.close {background: url("/spirentAssets/images/overlay/close.png") no-repeat 0 0;}</style><div id="video_window"></div>');
	
    $('a.videoLink').click( function () {
		
		var height = ($(this).hasClass("full")? 450 : 338);

	$('#video_window').html('<a class="close" style="display:none; height:42px; width:42px">close</a><div id="video_player" style="width:600px; height:'+height+'px;"></div>')
	var url = $(this)[0].href;

	$.blockUI.defaults.css = {
	    top: ($(window).height() - 500) / 2 + 'px',
	    left: ($(window).width() - 500) / 2 + 'px',
	    width: 'auto',
	    border: '5px solid #e4e4e4'
	};

	var flashvars = {
	    src: "/spirentAssets/flash/flowplayer.swf",
	    wmode: 'opaque'
	};
	var attributes = {
	    clip: {url: url,autoPlay: false,scaling:'fit'},
		canvas: {backgroundColor: '#FFFFFF'},
		plugins:{gatracker: {url: "/spirentAssets/flash/flowplayer.analytics.swf",events: {all: true},accountId: "UA-8100834-1"}}
	};

	// load the video player
	$f("video_player", flashvars, attributes);

	// hover tigger for close button
	$("#video_window").hover(function() {
	    $(this).find('.close').stop(true, true).fadeIn('fast');
	} , function() {
	    $(this).find('.close').stop(true, true).fadeOut('slow');
	});

	$.blockUI({message: $('#video_window')});
	$f("video_player").play();


	$(".blockOverlay, a.close").click(function () {
	    $.unblockUI();
	    $("div#video_window").empty();
	});
	return false;
    });
}


function youTubeLinks() {

    if($("a.youtube").length > 0){

	$("a.youtube")
	.click(function() {
	    var url = $(this)[0].href;
	    var vId = url.split('?v=')[1];

	    var player =  '<div id="vidPlayer"><a href="#" class="close">close</a> <div id="ytapiplayer">You need Flash player 8+ and JavaScript enabled to view this video.</div>';
	    player += '<script type="text/javascript">';
	    player += ' var params = { allowScriptAccess: "always", wmode: "transparent" }; var atts = { id: "myytplayer" };';
	    player += ' swfobject.embedSWF("http://www.youtube.com/v/'+ vId +'?enablejsapi=1&playerapiid=ytplayer", "ytapiplayer", "425", "356", "8", null, null, params, atts);';
	    player += '</script></div>';

	    $.blockUI.defaults.css = {
		top:  ($(window).height() - 500) /2 + 'px',
		left: ($(window).width() - 500) /2 + 'px',
		width: '467px'
	    };

	    $.blockUI({
		message : player
	    });

	    $(".blockOverlay, a.close") .click(function() {
		$.unblockUI();
	    });

	    return false;

	});


    }

}

function videoEmbed() {

    var flashvars = {};
    var params = {};
    params.wmode = "opaque";
    params.allowscriptaccess = "always";
    params.allowfullscreen = "true";

    $('.inlineVideo').each(function(i){

	$(this).css({
	    'border':'0',
	    'background':'transparent',
	    'padding':'0'
	});

	var div ='<div id="inlineVid'+i+'"></div>';

	$(this).wrapInner(div);

	flashvars.flv = $('a.videoDownload', this).attr('href');

	swfobject.embedSWF("/spirentAssets/flash/player.swf", "inlineVid"+i, "560", "365", "9.0.0",null, flashvars, params);
    });

}
function fnCustomForms(){
    if($('form.customForm').length>0){
	var form = $('form.customForm');

	//add a validation message
	form.prepend('<div class="validation"></div>').find('.validation', this).hide();

	//replace the input button with an image one
	var button = '<input type="image" src="/spirentAssets/images/buttons/submit-button.gif" alt="Submit" value="Submit" class="hov"/>';
	form.find(':submit').replaceWith(button);

	// Create a rule which sets max length
	$.validator.addMethod("cMaxLength", $.validator.methods.maxlength, $.format("Please enter less than {0} characters"));// leverage parameter replacement for maxlength, {0} gets replaced with 2

	// Set the max length 400 rule to a max length 400 class we can place on text areas.
	$.validator.addClassRules("maxlength400", {
	    cMaxLength: 400
	});

	//plugin the validation
	form.validate({
	    errorElement: "em",
	    errorPlacement: function(error, element) {
		//find the next break tag as placing the error next to the input breaks it when using radio buttons or checkboxes.
		element.nextAll('br:first').before(error);
	    },
	    ignoreTitle : true,
	    invalidHandler: function(form, validator) {
		var errors = validator.numberOfInvalids();
		if(errors){
		    var message = errors == 1
		    ? 'There are errors in 1 field. It has been highlighted'
		    : 'There are errors in ' + errors + ' fields. They have been highlighted';
		    $("div.validation").html('<em class="error">'+message+'</em>').show();
		}else{
		    $("div.validation").hide();
		}
	    }
	});
    }
}

// mini flyout on
function fnMiniFlyout() {
    if($('li.miniFO')){
	$('div.mfoWrap').hide();
	$('div.mfoWrap').parents('li')
	.hover(function() {
	    $(this).find('.mfoWrap').show();
	}, function() {
	    $(this).find('.mfoWrap').hide();
	});
	$('li.miniFO a:first')
	.bind('focus', function(event) {
	    $(this).parents('li');
	    $(this).parents('li').find('.mfoWrap').show();
	})
	.bind('blur', function(event) {
	    if(!$(this).find('a:focus')){
		$(this).parents('li').find('.mfoWrap').hide();
	    }
	});

	$('li.miniFO ul li a:last')
	.blur(function() {
	    $('div.mfoWrap').hide();

	});
    }

}
