// JavaScript Document
//container for the xml to be called later
var psmData;
var hideOverlayFlag = true;
var testimonialsData;


function initMenus(sectionName){
	$("div.menuBody ul li a").removeClass("selected");
	$("div.menuBody ul li a:contains('"+sectionName+"')").addClass("selected");
	$("p.breadcrumbs strong").text(sectionName);
	$("ul.footerMenu li a").removeClass("selected");
	$("ul.footerMenu li a:contains('"+sectionName+"')").addClass("selected");
}

//loading PSM data and init table
function loadPsmData(){
	$.ajax({
		type: "GET",
		url: "data/psm.xml",
		dataType: "xml",
		success: function(xml) {
			psmData = xml;
			//adding sorter to empty table
			$.tablesorter.defaults.widgets = ['zebra'];
			//$.tablesorter.defaults.sortList = [[0,0]]; 
			$("#psmTable").tablesorter();
			$(psmData).find("university").each(function(){
				var uName = $(this).attr("name");
				var uStatus = $(this).attr("status");
				//alert(uName +" -- "+ uStatus);
				if(uStatus == "true"){
					$(this).find("program").each(function(){
						//check for status set to true to display in table
						var status = $(this).find("status").text();
						if (status =="true"){
							//check for url to set title link
							var title = $(this).find("title").text();
							if( $.trim($(this).find("url").text()) !== ""){
								title = "<a href='" + $(this).find("url").text() + "' target='_blank'>" + title + "</a>";
							}
							//check for brochure to set title link
							var brochure = "";
							if( $.trim($(this).find("brochure").text()) !== ""){
								brochure = " <a href='" + $(this).find("brochure").text() + "' target='_blank'><img src='images/icon_brochure.png' border='0' align='baseline' alt='Download program brochure' title='Download program brochure'></a>";
							}
							//append row to table
							$("#psmTable tbody").append("<tr><td>"+uName+"</td><td>"+ title + brochure + "</td><td>"+$(this).find("industry").text()+"</td><td>"+$(this).find("date").text()+"</td><td><a href='mailto:"+$(this).find("email").text()+"'>"+$(this).find("contact").text()+"</a></td></tr>").parent().trigger("update");
						}
					});
					$("#psmTable").trigger("sorton", [[[0,0]]]);
					//$("#psmTable").trigger("applyWidgetId", "zebra");
					
				}else{
					//Hide from map
					$("#"+ $(this).find("code").text()).hide();
				}
				
				//add university options to filter form
					$("#filterInstitution").append($("<option>"+uName+"</option>"));
			});
		}
	});
}

/*loading TESTIMONIALS data*/
function loadTestimonialsData(){
	$.ajax({
		type: "GET",
		url: "data/testimonials.xml",
		dataType: "xml",
		success: function(xml) {
			testimonialsData = xml;
			$test = $(testimonialsData).find("testimonial");
			$test.each(function(){
				//alert($(this).find("author").text());
			});
			var randomNum=Math.floor(Math.random() * $test.length);
			//alert(randomNum);
			var el = $test.get(randomNum);
			//alert(el.find("author").text());
			//alert($(el).find("descr").text());
			$("#quoteAuthor").html($(el).find("author").text());
			$("#quoteAuthorTitle").html($(el).find("title").text());
			$("#quoteDescr").html($(el).find("descr").text());
			$("#quoteBox").css("background-image","url("+$(el).find("image").text()+")");
		}
	});	
}

/*initializing PSM TableSorter*/
function initTableSorter(){
	
}

/*MAPS functions*/
function showOverlay(){
	var uCode = $(this).attr("id");
	//alert($(this).position().top);
	//alert(psmData);
	$(psmData).find("university").each(function(){
		if(uCode == $(this).find("code").text()){
			//set mapOverlay code to the active university selected
			$("#mapOverlay").data("code", uCode);
			
			var uName = $(this).attr("name");
			var uLocation = $(this).find("location").text();
			var uURL = $(this).children("url").text();
			$("#mapOverlay h3.uName").text(uName);
			$("#mapOverlay p.uLocation").text(uLocation);
			$("#mapOverlay a.uLink").attr("href",uURL);
			
			//remove old programs from the list
			$("ul.uProgs li").remove();
			
			//repopulate programs
			$(this).find("program").each(function(){
				//check for status set to true to display in table
				var status = $(this).find("status").text();
				if (status =="true"){
					//check for url to set title link
					var title = $(this).find("title").text();
					if( $.trim($(this).find("url").text()) !== ""){
						title = "<a href='" + $(this).find("url").text() + "' target='_blank'>" + title + "</a>";
					}
					//check for brochure to set title link
					var brochure = "";
					if( $.trim($(this).find("brochure").text()) !== ""){
						brochure = " <a href='" + $(this).find("brochure").text() + "' target='_blank'><img src='images/icon_brochure.png' border='0' align='baseline' alt='Download program brochure' title='Download program brochure'></a>";
					}
					//append row to table
					$("ul.uProgs").append("<li>"+ title + brochure +" ("+$(this).find("date").text()+")</li>");
				}
			});
		}
	});
	
	//Position overlay to pin on the map
	if(isIE()){
		$("#mapOverlay").position({
			my:"left bottom", 
			at:"left top", 
			of:$(this),
			offset:"-40 0",
			collision:"fit"
			}).show();
	}else{
		
		$("#mapOverlay").position({
			my:"left bottom", 
			at:"left top", 
			of:$(this),
			offset:"-40 0",
			collision:"fit"
			}).animate({opacity: "show"}, "slow");
	}
}
	
function hideOverlay(){
	if(hideOverlayFlag){
		if(isIE()){
			$("#mapOverlay").hide();
		}else{
			$("#mapOverlay").animate({opacity: "hide"}, "slow");
		}
	}
}

function showOverlaySelf(){
	//do nothing when user has mouse on overlay
}
	
function hideOverlaySelf(){
		alert("intent to leave activated");
		hideOverlay();
}



//Initializing MAP
function initMap(){
	//setting time delay for map popup
	var config = {    
		 sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 200, // number = milliseconds for onMouseOver polling interval    
		 over: showOverlay, // function = onMouseOver callback (REQUIRED)    
		 timeout: 500, // number = milliseconds delay before onMouseOut    
		 out: hideOverlay // function = onMouseOut callback (REQUIRED)    
	};
	$("#flmap a").hoverIntent( config );
	
	$("#flmap a").hover(
		function () {
			$(this).children("img").attr("src","images/pin_over.png");
			hideOverlayFlag = false;
			
		}, 
		function () {
			$(this).children("img").attr("src","images/pin.png");
			hideOverlayFlag = true;
		}

	);
	
	//OVERLAY
	$("#mapOverlay").hover(
		function () {
			hideOverlayFlag = false;
		}, 
		function () {
			hideOverlayFlag = true;
			hideOverlay();
		}
	);
}



//initialize featured Box slider
function initFeaturedBox(){
	    var $panels = $('#slider .scrollContainer > div');
    var $container = $('#slider .scrollContainer');

    // if false, we'll float all the panels left and fix the width 
    // of the container
    var horizontal = true;

    // float the panels left if we're going horizontal
    if (horizontal) {
        $panels.css({
            'float' : 'left',
            'position' : 'relative' // IE fix to ensure overflow is hidden
        });

        // calculate a new width for the container (so it holds all panels)
        $container.css('width', $panels[0].offsetWidth * $panels.length);
    }

    // collect the scroll object, at the same time apply the hidden overflow
    // to remove the default scrollbars that will appear
    var $scroll = $('#slider .scroll').css('overflow', 'hidden');

    // apply our left + right buttons
    /*$scroll
        .before('<img class="scrollButtons left" src="images/scroll_left.png" />')
        .after('<img class="scrollButtons right" src="images/scroll_right.png" />');
*/
    // handle nav selection
    function selectNav() {
        $(this)
            .parents('ul:first')
                .find('a')
                    .removeClass('selected')
                .end()
            .end()
            .addClass('selected');
    }

    $('#slider .navigation').find('a').click(selectNav);

    // go find the navigation link that has this target and select the nav
    function trigger(data) {
        var el = $('#slider .navigation').find('a[href$="' + data.id + '"]').get(0);
        selectNav.call(el);
    }

    if (window.location.hash) {
        //alert(window.location.hash.substr(1));
		trigger({ id : window.location.hash.substr(1) });
    } else {
        $('ul.navigation a:first').click();
    }

    // offset is used to move to *exactly* the right place, since I'm using
    // padding on my example, I need to subtract the amount of padding to
    // the offset.  Try removing this to get a good idea of the effect
    var offset = parseInt((horizontal ? 
        $container.css('paddingTop') : 
        $container.css('paddingLeft')) 
        || 0) * -1;


    var scrollOptions = {
        target: $scroll, // the element that has the overflow

        // can be a selector which will be relative to the target
        items: $panels,

        navigation: '.navigation a',

        // selectors are NOT relative to document, i.e. make sure they're unique
        prev: 'img.left', 
        next: 'img.right',

        // allow the scroll effect to run both directions
        axis: 'xy',

        onAfter: trigger, // our final callback

        offset: offset,

        // duration of the sliding effect
        duration: 500,

        // easing - can be used with the easing plugin: 
        // http://gsgd.co.uk/sandbox/jquery/easing/
        easing: 'swing'
    };

    // apply serialScroll to the slider - we chose this plugin because it 
    // supports// the indexed next and previous scroll along with hooking 
    // in to our navigation.
    $('#slider').serialScroll(scrollOptions);

    // now apply localScroll to hook any other arbitrary links to trigger 
    // the effect
    $.localScroll(scrollOptions);

    // finally, if the URL has a hash, move the slider in to position, 
    // setting the duration to 1 because I don't want it to scroll in the
    // very first page load.  We don't always need this, but it ensures
    // the positioning is absolutely spot on when the pages loads.
    scrollOptions.duration = 1;
    $.localScroll.hash(scrollOptions);
}

//initialize Industry Sector Menu
function initIndustrySector() {
 $('#industrySectorBox div').hide();
 $('#industrySectorBox li:first div').show();
 $('#industrySectorBox li:first h3 a').addClass("selected");
 $('#industrySectorBox li h3 a').click(function() {
	  var checkElement = $(this).parents("li").children("div");
	 if((checkElement.is('div')) && (checkElement.is(':visible'))) {
	 return false;
	  }
	  if((checkElement.is('div')) && (!checkElement.is(':visible'))) {
	  $('#industrySectorBox div:visible').slideUp('normal');
	  $('#industrySectorBox li h3 a').removeClass("selected");
	  $(this).addClass("selected");
	  checkElement.slideDown('normal');
	  return false;
	  }
	  }
  );
}

function isIE(){
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}
