var Walden = {};

Walden.popupVideoHTML = '<div id="jsVideoPlayer" class="jsVideoPlayerLoader"><div id="jsVideoPlayerClose"></div></div><div id="jsVideoPlayerScreen"></div>';


$(document).ready(function(){
	//    jQuery.each($('ul.tabs'), function(index, value) {
	//        $(value).tabs();
	//    });
	
	//    $("UL.hr-tabs").tabs();
	
	//    jQuery.each($('.in-tabs > UL'), function(index, value) {
	//        $(value).tabs();
	//    });
	
	/* VR 2009.02.04*/ 
	// table zebra stripes
	$('div.center table tr:nth-child(odd)').addClass('odd');
	
	$('#iframe-container table tr:nth-child(odd)').addClass('odd');
	
	// :psuedo class fix
	$('ul>li:first-child, tr>td:first-child, tr>th:first-child').addClass('firstChild');
	$('ul>li:last-child,  tr>td:last-child,  tr>th:last-child').addClass('lastChild');
	
	// highlight first td
	$('div.center table tr td:first-child').addClass('highlight');
	
	$('ul.xtabs').tabs();
	
	// add functions and HTML to style the primary nav
	$('ul#main-menu>li').each(function(i){
		$(this)
			.attr('id', 'mainMenuLi' + i)
			.find('a').eq(0).append('<span></span>') // the SPAN holds the BG image of the nav
			.end()
			.end()
			.hover(
				function () {
					$('ul#main-menu li.active').removeClass('active').addClass('activeOff');
					$(this).addClass('hover');
				}, 
				function () {
					$('ul#main-menu li.activeOff').removeClass('activeOff').addClass('active');
					$(this).removeClass('hover');
				}
			);
	});
	
	// add slider functionality
	$('div.slider h1').click(function(i){
		if($(this).is('.active') == false) {
			$(this)
				.parent()
				.find('h1.active')
				.removeClass('active')
				.next()
				.slideUp()
				.end()
				.end()
				.end()
				.addClass('active')
				.next()
				.slideDown();
		}
	});

	// two-column-content float fix
	$('#two-column-content div.promo-image').each(function(i){
		if(i % 2) {
			$(this).after('<div style="clear: both"></div>');
		}
	});


           $('div#liketo h3').each(function(i){
                if(i === 0){
                    $(this).addClass("open"); // set the first one OPEN by default
                }
                else {
                    $(this).next().hide(); // hide all others
                }
                $(this).find('a').click(function(){
                    // if the one clicked is already open, do nothing
                    if($(this).parents('h3').is('.open') === false) {
                        $(this).parents('div#liketo').find('h3.open').removeClass('open');
                        $(this).parents('div#liketo').find('div.container:visible').slideUp();
                        $(this).parent().next().slideDown();
                        $(this).parent().addClass('open');
                    }
                    return false;
                });
            });

	// onclick hander for links defined as popup windows (ds)
	    $("a.popup").click(function () {
	        var args = getPageandArgs($(this).attr("href"));
	        var popupwin = newpopup($(this).attr("href"),args.name,args.width,args.height,args.offsetx,args.offsety,args.toolbar,args.scrollbars,args.resizable);
	        popupwin.focus();
	        return false;
    	});
    	
    	// onclick handler for print tracking via SiteCatalyst
    	$("a[href='javascript:window.print()']").click (function () {
    		SiteCatalyst.sendPrintEvent();
    	});
    	
    	// onclick handler for continue button on the short homepage request info form 
    	$("form div input[src='/_res/img/continue.gif']").click (function () {
    		SiteCatalyst.sendShortFormContinueEvent();
    	});
    	
    	// Replace link to Request Information form with link to the optimal two step form 05.06.2009 (ds)
    	$("a[href='/Forms/Request-Information-TwoStep.aspx']").attr("href","/Forms/Request-Information-TwoStep.aspx?FormID=2");
	$("a[href='/Forms/Request-Information.aspx']").attr("href","/Forms/Request-Information-TwoStep.aspx?FormID=2");
	
	$(".loading").css({'display':'none'});
		
	$("#rotator").after('<div id="controls">').cycle({
		pager : '#controls',
		speed: 'slow',
		timeout: 7000,
		fx: 'fade',
		pagerClick: pauseSlideShow
	});	
	$("input.referanother").click(function () {
      		$(".extrarows").show();
      		$("input.referanother").hide();
    	}); 
	 
	$("a.media").click(function(){$(this).blur();$("body").append(Walden.popupVideoHTML);$("#jsVideoPlayerScreen").css("opacity",0.7);var e=$(this).attr("class").replace("media ","");var k=$(this).attr("href");var g=$(this).offset().left;var f=$(this).offset().top;var b=$(this).width()-10;var i=$(this).height()-10;if($(this).find("img").size()===1){b=$(this).find("img").width()-10;i=$(this).find("img").height()-10;g=$(this).find("img").offset().left;f=$(this).find("img").offset().top}if(b<1){b=1}if(i<1){i=1}var j=parseInt(((e.match(/w:(\d+)/)||[])[1]||0),10);var d=parseInt(((e.match(/h:(\d+)/)||[])[1]||0),10);var a=parseInt($(window).width()/2,10)-parseInt((j/2),10);var m=parseInt($(window).scrollTop()+140,10);$("#jsVideoPlayer").css("width",b+"px").css("height",i+"px").css("top",f+"px").css("left",g+"px").css("display","block").animate({width:j+"px",height:d+"px",left:a-5+"px",top:m-5+"px"},250,function(){$(this).append('<div class="getFlashPlayer"></a>').find("div.getFlashPlayer").click(function(){location.href="http://www.adobe.com/go/EN_US-H-GET-FLASH"}).end().removeClass("videoPlayerLoader").find("div.getFlashPlayer").jmedia({version:"9,0"},{src:k+"?type=.swf",width:j,height:d,quality:"best"})});$("#jsVideoPlayerScreen, #jsVideoPlayerClose").click(function(){$("#jsVideoPlayer").addClass("videoPlayerLoader").css("height",$("#jsVideoPlayer").height()).html("").animate({width:b+"px",height:i+"px",top:f+"px",left:g+"px",opacity:0.1},250,function(){$("#jsVideoPlayer, #jsVideoPlayerScreen").remove()})});return false});

	$(".video-section h2").click (function () { $(this).toggleClass("closed").next(".video-section-more").slideToggle("normal").end().next(".related-videos").slideToggle("normal");})
			      
	$("a[rel='transparency']").colorbox({width:"650px", height:"650px"});
	
	//Social Media Click tracking
	$("a.sm-facebook").click (function () {SiteCatalyst.sendSocialMediaClickEvent("Facebook");});
	$("a.sm-linkedin").click (function () {SiteCatalyst.sendSocialMediaClickEvent("LinkedIn");});
	$("a.sm-myspace").click (function () {SiteCatalyst.sendSocialMediaClickEvent("Myspace");});
	$("a.sm-youtube").click (function () {SiteCatalyst.sendSocialMediaClickEvent("YouTube");});
	$("a.sm-twitter").click (function () {SiteCatalyst.sendSocialMediaClickEvent("Twitter");});
	
	$("#RequestInformationTwoStep_PersonalInfoButton").attr("value", "");
	$("#RequestInformationTwoStep_EducationalInfoButton").attr("value", "");

	progressControls = new Array();
        $(".required").each(function(i) { if (!IsNullOrBlank($(this).val())) { UpdateProgressBar(this); } });
        $(".required").blur(function() { if (!IsNullOrBlank($(this).val())) { UpdateProgressBar(this); } });

});
function pauseSlideShow() {
	$('#rotator').cycle('pause');
}

// New function to open a popup window
// undefined parameters are initialzed to default values
function newpopup(loc, name, width, height, offsetx, offsety, toolbar, scrollbars, resizable){
 	//Check for width and height, if undefined then define as screen width and height
 	if (!width) {width=screen.width;}
 	if (!height) {height = screen.height;}
 	//Set default for popup offsets
  	if(!offsetx && !offsety){
  		var scr_x = screen.width;
  		var scr_y = screen.height;
  		var offsetx = (scr_x/2)-(width/2);
  		var offsety = (scr_y/2)-(height/2);
  	}
	var optToolbar, optScrollbars, optResizable;
	//Check for nulls and assign defaults if we find one, otherwise assign the passed value
	(!name) ? optName = "popup" : optName= name;
	(!toolbar) ? optToolbar = "toolbar=no" : optToolbar = "toolbar=" + toolbar;
	(!scrollbars) ? optScrollbars = "scrollbars=no" : optScrollbars = "scrollbars=" + scrollbars;
	(!resizable) ? optResizable = "resizable=no" : optResizable = "resizable=" + resizable;
	var options = optToolbar + ",location=no, directories=no, status=no, menubar=no," + optScrollbars + "," + optResizable + ", width="+width+", height="+height+", left="+offsetx+", top="+offsety;
	return window.open(loc, optName, options);
}

// Function to parse an href value and return an object
// with the href page value and any arguments passed as well.
function getPageandArgs(href) {
	var args = new Object( );
    	var url = href.split("?");
    	args["page"] = url[0];
    	var query = url[1];
    	// Only parse query parameters if there are some
    	if (query) {
    		var pairs = query.split("&");
		for(var i = 0; i < pairs.length; i++) {
			var pos = pairs[i].indexOf('=');
			if (pos == -1) continue;
			var argname = pairs[i].substring(0,pos);
			var value = pairs[i].substring(pos+1);
			value = decodeURIComponent(value);
			args[argname] = value;
		}
    	}
    	return args;
}

/*
 * This function parses ampersand-separated name=value argument pairs from
 * the query string of the URL. It stores the name=value pairs in
 * properties of an object and returns that object. Use it like this:
 *
 * var args = getArgs( );  // Parse args from URL
 * var q = args.q || "";  // Use argument, if defined, or a default value
 * var n = args.n ? parseInt(args.n) : 10;
 */
function getArgs( ) {
    var args = new Object( );
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split("&");                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos+1);    // Extract the value
        value = decodeURIComponent(value);        // Decode it, if needed
        args[argname] = value;                    // Store as a property
    }
    return args;                                  // Return the object
}

var SiteCatalyst = {};

SiteCatalyst.sendVideoStartEvent = function (title) {
	s=s_gi('laureateWaldenU');
        s.linkTrackVars= 'prop7,eVar7,events';
        s.linkTrackEvents= 'event6';
        s.prop7 = title;
        s.eVar7 = title;
	s.events = 'event6';
        s.tl(this,'o', 'Video Started');
}

SiteCatalyst.sendVideoCompleteEvent = function (title) {
	s=s_gi('laureateWaldenU');
        s.linkTrackVars= 'prop7,eVar7,events';
        s.linkTrackEvents= 'event7';
        s.prop7 = title;
        s.eVar7 = title;
	s.events = 'event7';
        s.tl(this,'o', 'Video Completed');
}

SiteCatalyst.sendPrintEvent = function () {
	s.linkTrackVars = 'eVar8,events';
	s.linkTrackEvents = 'event8';
	s.eVar8 = s.pageName;
	s.events = 'event8';
	s.tl(this,'o', 'Page Printed');
}

SiteCatalyst.sendSocialMediaClickEvent = function (link) {
	s.linkTrackVars = 'prop18,eVar18';
	s.eVar18 = link;
	s.prop18 = link;
	s.tl(this,'o', 'Social Media Clickthrough');
}

SiteCatalyst.sendShortFormContinueEvent = function () {
	s.linkTrackVars = 'events';
	s.linkTrackEvents = 'event14';
	s.events = 'event14';
	s.tl(this,'o', 'Request Info Short Form-Continue');
}

SiteCatalyst.setSectionLevelProps = function (lstr) {
	var c = lstr.split("|");
	if (c.length > 3) {
		s.prop21 = c.slice(0,4).join("|");
	}
	if (c.length > 2) {
		s.prop20 = c.slice(0,3).join("|");
	}
	if (c.length > 1) {
		s.prop19 = c.slice(0,2).join("|");
	}
}

var progressControls = new Array();

function pageLoad() {
	$("#RequestInformationTwoStep_Wizard1_ddlCountry").unbind();
	$("#RequestInformationTwoStep_Wizard1_ddlCountry").change(function() {
	if ($(this).val() != null || $(this).val() != "") 
	    {
		$(".countrycode").show();
		$("#RequestInformationTwoStep_Wizard1_tbHomeCountryCode").val(CountryCodes[$(this).val().toString()]);
		$("#RequestInformationTwoStep_Wizard1_tbWorkCountryCode").val(CountryCodes[$(this).val().toString()]);
	    }
	    if ($(this).val() == "USA")
	    {
		$(".countrycode").hide();
	    }
	});
	$(".required").each(function(i) { if (!IsNullOrBlank($(this).val())) { UpdateProgressBar(this); } });
	$(".required").blur(function() { if (!IsNullOrBlank($(this).val())) { UpdateProgressBar(this); } });
	
	$(".areacode,.phone1,.phone2").keyup(function() {
	    //check if the length is equal to the max length
	    if ($(this).val().length >= parseInt($(this).attr("maxlength"))) {
		$(this).next("input").focus();
	    }
	});
}

function UpdateProgressBar(input) {
//push this control on a list of elements already adjusted
//update to 100% when highest level of edu is selected
if (!progressControls.containsValue(input.name))
{
    progressControls.push(input.name);            
    var progressBarWidth = $(".progressbar-current").css("width");
    progressBarWidth = progressBarWidth.replace("px", "");
    progressBarWidth = parseInt(progressBarWidth);
    if (progressBarWidth < 200) {
	progressBarWidth += 20;
	$(".progressbar-current").animate({ width: progressBarWidth });
    }
}
}

Array.prototype.containsValue = function(value) {
for (var i=0;i<this.length;i++)
{
    if (this[i] == value){
	return true;
    }
}
return false;
}


function IsNullOrBlank(s) {

if (s == "" || s == null || s == "none") {
    //console.log("true: " + s);
    return true;
}
else {
    //console.log("false: " + s);
    return false;
}
} 

