/*********************************************************************************
 * 
 * core.js, this is the global functionality required by the site, the file must be included
 * on the page AFTER the jquery js include and BEFORE any page specific js.
 * 
 *********************************************************************************/

var core = {};
core.callback = {};



//default loader bar for ten lists
core.ten_loader = "<p><img src='/img/ui/l-anim.gif' alt='loading' /></p>";
//the class that has display:none in global.css
core.hidden_class = ".dNone";

/**
 * Opens the third party video player
 **/
core.open_video_player = function show_player(id) {
        var url = 'http://www.seethejob.com/video_player_myfuture/playermyfuture.asp?cid='+id;
        var mywin = window.open(url, 'myfuture_player', 'width=762,height=532,toolbar=0,resizable=0,location=0');
    }

/**
  * Sets a "sticky" value for the career pathway module
  * 
  * @hash - the pathways bookmark
  **/
core.set_pathway_hash= function(hash, debug)
{
	
	if(hash && hash !="")
	{
	  $.get("/ajax/pathwayHash", {"hash":hash}, function(data){
		if(debug && debug==true)
		{
			alert(data);
		}
	  });	
	}
	
	return false;
}
  
	
	
/**
 * Opens a chart expander
 **/
core.handle_chart_expander = function(obj)
{

	var the_id = obj.id;
	var id_ar = the_id.split("_");
	var action = id_ar[1];
	var target = id_ar[0];
	var hider = id_ar[2];
	
	$("#"+the_id).hide();
	$("#"+target+"_"+hider+"_"+action).show();
	$("#"+target+"_"+hider).hide();
	$("#"+target+"_"+action).fadeIn();
	
	return false;
}



/**
 * resets a text field if @val is not blank
 * 
 **/
core.reset_text_field = function(val)
{
  var r = '';
	if(val && val != ''){
	  r = val;
	}
	return r;
}

/**
 * determines if winnow a checkbox should be checked
 * */
core.reset_checkbox= function(val){
				return (val=="yes" ? true : false);
}

/**
 * Handles location tabbing
 **/
core.handle_location_tabs = function(obj, str)
{
	var type_ar = obj.id.split("_");
	$("#ss-zip").val("");
	$("#ss-loc-tabs > li").removeClass("sel");
	
	
	$("#ss-loc_"+type_ar[1]).addClass("sel");
		
	$("#ss-loc-holder > fieldset").hide();
		
	$("#fs-loc_"+type_ar[1]).show();
	$("#ss-loc-search-on").val(type_ar[1]);
}

/**
 * Opensa qtip box
 * */
core.init_qtip = function(qt)
{
   var the_id = qt.id;
   var the_text = $("#qt_"+the_id).html();
   var qt_pos = qt.rel;
   var the_title = qt.name;
   var target_pos = "rightBottom";
   var tip_pos = "leftTop";
   
   if(qt_pos == "topLeft"){
	target_pos = "rightTop";
	tip_pos = "leftBottom";
   }
   
   if(qt_pos == "middleLeft"){
	target_pos = "rightMiddle";
	tip_pos = "leftMiddle";
   }
   
   if(qt_pos == "middleRight"){
	target_pos = "leftMiddle";
	tip_pos = "rightMiddle";
   }
   
   if(qt_pos == "topRight"){
	target_pos = "leftTop";
	tip_pos = "rightBottom";
   }
   if(qt_pos == "bottomRight"){
	target_pos = "leftBottom";
	tip_pos = "rightTop";
   }
   
   
   // Match all link elements with href attributes within the content div
   $(qt).qtip({
	content: {
		text: the_text, // Give it some content, in this case a simple string
		title: {text: the_title}
	},
	hide: { when: 'mouseout', fixed: true },
	classes: {content: "qtip-tip"},
	style: { name: "dark", width: 350, border:{color: "#aaaaaa", width: 2, radius: 3} },
	position: {
		corner: {
			target: target_pos,
			tooltip: tip_pos
		}
	}
	

	
   });
}

/**
 * Handles the hiding/showing of the generic tab structure
 * requires that links and content wells folloe the link-id_target and content-id_target model, where "target" is teh same.
 * ie: clicking a-search_thetype will make the content in div-search_thetype appear
 **/
core.handle_tabs = function(clicked, tab_target, content_target, tab_class, content_selector, hard_id, id_callback)
{
	if(!clicked)
	{
		var the_id = hard_id;
		var tab_id = "#a-"+content_selector+"_"+the_id;
	}
	else
	{
		var id_ar = clicked.id.split("_");
		var the_id = id_ar[1];
	}
	
	var content_div = "#"+content_selector+"_"+the_id;
	
	if(tab_class == null){tab_class="aFindOn";} //most common class to use
	
	$(tab_target).removeClass(tab_class);
	$(content_target).hide();
	
	
	
	if(!clicked)
	{
		$(tab_id).addClass(tab_class);
	}
	else
	{
		$(clicked).addClass(tab_class);
	}
	
	
	$(content_div).show();
	
	if(id_callback){
		id_callback(the_id);
	}
	
	$(clicked).blur();
}


/**
 * core.get_check_box_yes() - aids in search for schools and careers
 * returns a yes if a checkbox is checked and a no_pref if not 
 * 
 * @id - the DOM id of a check box
 * returns: string
 */
core.get_check_box_yes = function(id)
{
	if($("#"+id).is(':checked')){
		return "yes";
	}else{
		return "no_pref";
	}
}

/**
 * Checks if a string is blank. if so appends an error message to the target
 * if no target is specified, it alerts it.
 * 
 * usage: core.check_if_blank(value, "This can't be blank", ["#holderDiv"]);
 */
core.check_if_blank = function(string, message, target)
{
	if(!string || string==""){
		if(!target || target==""){alert(message);}
		else{var pre = "<p class='errors'>"+message+"</p>"; $(target).prepend(pre);}	
	}
}

/**
 * Takes the @href of a favorite link, splits it and then adds that item to the 
 * user's favorites
 */
core.handle_add_to_favorites = function(href)
{
	var ha = href.split("?");
	core.basic_ajax(ha[0], ha[1], "html", "#div-favorite-link");
}

/**
 * Takes the @href of a favorite link, splits it and then removes that item from the 
 * user's favorites
 */
core.handle_remove_from_favorites = function(href, rel)
{
	
	var ha = href.split("?");
	core.basic_ajax(ha[0], ha[1], "html", "#div-favorite-link");
	
	if(rel != "")
	{
		rel_ar = rel.split("_");
		the_div = "#rt_"+rel_ar[1];
		
		$(the_div).slideUp("fast", function(){
			//callback, see if all are hidden, if so show the message.
			$show_count =0;
			$(".divCrDetails").each(function(){
				if($(this).is(":visible")){
					$show_count++;
				}
			});
			if($show_count < 1){
				$("#favorite-holder").html("<p class='no-favorites'><b>You have removed all of your favorites for this section.</b></p>");
			}
		});
	}	
}


/**
 * show_address() - used to show a google map for @address, to be displayed in @target
 * requires setting $use_map = true in the page's controller
 * 
 */
core.show_address = function(address, target){

var map = new GMap2(document.getElementById("schoolMap"));
var geocoder = new GClientGeocoder();

  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
      	
      	var mapControl = new GMapTypeControl();
		
		map.addControl(mapControl);
		map.addControl(new GSmallMapControl());
        
        map.setCenter(point, 13);
        
        var marker = new GMarker(point);
        map.addOverlay(marker);
       
      }
    }
  );
}

/**
 * gets a QS param
 * */

/*
core.get_qs_param = function(key, force_url_, default_)
{
  
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = null;
  
  if(force_url_ && force_url_ != null) {
	qs = regex.exec(force_url_);
  } else {
	qs = regex.exec(window.location.href);
  }
  
  if(qs == null) {
    return default_;
  } else {
    return qs[1];
  }
  
}
*/

/**
 * Uses the jquery ajax function to load full views (think full content well replace)
 * usually called from within individual page js files
 * 
 * usage: core.basic_ajax("/ajax/handleAjax", "?dataObject=foo&DataObject2=bar", "html", "#divContainer")
 */
core.basic_ajax = function(theAction, sentData, returnType, target, loading_message) {
	
	
	var r_data = "";
	$(target).html(loading_message);
	
	//jquery action
	 $.ajax({	
			type: "GET",
			url: theAction,
			data: sentData,
			dataType: returnType,
			success: function(theData, msg){
			
			$(target).html(theData);
			r_data = theData;
		}
		});
	 
	           
	 return r_data;
}

/**
 * Opens and closes the search box
 **/
 core.toggle_search_box = function()
 {
	var bg_image = "/images/global/quick_search.gif";
	var curr_image = $("#divQckSrch h5").css('backgroundImage');
	
	if(curr_image.indexOf('quick_search_off.gif')==-1){
		bg_image = "/images/global/quick_search_off.gif";
		$("#divQSrchBox").slideUp("fast");
	}
	else{
		$("#divQSrchBox").show();
	}
	
	$("#h5-qs-toggle").css('background','url('+bg_image+')');
	
	
 }
/**
 *  Uses jQuery to show or hide the contents of long paragraphs
 *  takes a param to be attributed to teh p's id.
 */
core.toggle_long_text = function(theId)
{
	if($(theId).text() == "Show More"){
			$(theId).text("Show Less");
		}else{
			$(theId).text("Show More");
		}
		
		$(theId+"1").toggle();
		$(theId+"2").toggle();
}

/**
 * Determines whether or not the quick search should be open
 * on page load and if so, which page it should be.
**/
 core.test_open_search = function()
 {
	var r = false;
	var path = document.location.pathname;
	
	if(path == "/" || path == "/search"){r = "entire";a="/search";}
	
	if(path=="/careers" || path=="/careers/searchresults"){r = "careers";}
	
	if(path=="/schools" || path == "/schools/searchresults"){r = "college";}
	
	core.callback.open_search(r);
 }

/*
// sets Omniture event if referring domain is not myfuture.com, and sets event7 if it is. 
core.campaign_landing_page = function(type) {
    var r = ""
    if(document.referrer.indexOf("myfuture.com") == -1)
    {
        if(type=="eVar" || !type)
        {
            r = s.pageName;
        }
    }
    else
    {
        if(type=="event")
        {
            r = ",event7";
        }
    }
    return r;
}
*/

// Used to calculate bounce rate. Written by Alex Hanks @ Omniture.
entered = function(type) {
    var r = ""
    if(document.cookie.match('s_entered'))
    {
        if(type=="event")
        {
            r = ",event19"; // Non-Bounce Event - configured to be set once per visit 
        }
    }
    else
    {
        if(type=="event")
        {
            r = ",event18"; s.c_w('s_entered','s_entered',0); // New Entry Event - configured to be set once per visit
        }
    }
    return r;   
    alert(r);
}



/*********************************** CALLBACK FUNCTIONS  *************/

core.callback.open_search = function(target)
{
	
	//naming hacks - nobody's is perfect :/
	if(target=="entire site"){target = "entire";}
	
	var form_action = "/search";
	var the_class = target+"-on";
	
	if(target!="")
	{
		$("#divQSrchBox").show();
		
		
		
		if(target=="careers"){form_action="/careers/searchresults";}
		if(target=="college"){form_action="/schools/searchresults";}
		if(target=="articles"){form_action="/articles/searchresults";}
		
		$("#divQSrchBox > ul > li > a").removeClass();
		$("#quick-search-form").attr({
				action:form_action
			});
		$("#a-qs-"+target).addClass(the_class);
		
		$(".qs-span").hide();
		
  		$("#span-qs-"+target).removeClass("hidden");
		$("#span-qs-"+target).show();
	}
}

//shows or hides the region map on the college home page
core.callback.handle_region_map = function(id)
{
	(id != "location") ? $("#school-location-elements").hide() : $("#school-location-elements").show();
}


/******************************* ON PAGE LOAD ***********************************************************/
$(function(){

if($("#flashcontent").length > 0)
{

}
 /**
  * Gets omniture vars based on string matching for any link that strats with http...
 **/
$('a[href^="http"]').bind("click", function(e){

        var s=s_gi('mullenmyfuture-new');
            if(window.location.hostname == "beta.myfuture.com" || window.location.hostname.indexOf("localhost") != -1)
            {
                s=s_gi('mullenmyfuture-new-beta');
            }
	if(this.rel != "entire" && !$(this).hasClass("iframe"))
		{
			var href = $(this).attr("href");
			var linkText = $(this).text().toLowerCase();

            
			s.linkTrackVars="eVar1,eVar3,prop6,events";
			  
			if(href.indexOf("todaysmilitary.com") == -1)
			{
                s.linkTrackEvents="event3";
				s.events = "event3";
				
				//set the value for eVar1 based on the link text or the href
				if(href.indexOf(".gov") != -1)
                {
					s.eVar1 = "General Government";
				}
				
				if((href.indexOf(".edu") != -1) || (this.rel == "school"))
                {
					s.eVar1 = "School";
				}
				
				if(linkText.indexOf("bls") != -1)
                {
					s.eVar1 = "BLS";
				}
				
				if(linkText.indexOf("dhra") != -1)
                {
					s.eVar1 = "DHRA";
				}	
				
				if(linkText.indexOf("army") != -1)
                {
					s.eVar1 = "Army";
					if(linkText.indexOf("reserve") != -1)
                    {
						s.eVar1 += " Reserve";
					}
				}		
  
				if(href.indexOf("goguard") != -1 || linkText.indexOf("ngb") != -1 || href.indexOf("nationalguard") != -1)
                {
					s.eVar1 = "Army National Guard";
				}
				
				if(linkText.indexOf("marine") != -1 || (href.indexOf("usmc") != -1))
                {
					s.eVar1 = "Marines";
					if(href.indexOf("reserves.jsp") != -1)
                    {
						s.eVar1 += " Reserve";
					}
				}
				
				if(linkText.indexOf("navy") != -1)
                {
					s.eVar1 = "Navy";
					if(linkText.indexOf("reserve") != -1)
                    {
						s.eVar1 += " Reserve";
					}
				}
				
				if((href.indexOf("afsv") != -1) || (href.indexOf("airforce") != -1) || (linkText.indexOf("afsv") != -1) || (href.indexOf("afreserve") != -1))
                {
					s.eVar1 = "Air Force";
					if((linkText.indexOf("reserve") != -1) || (href.indexOf("afreserve") != -1))
                    {
						s.eVar1 += " Reserve";
					}
				}
				
				if((href.indexOf(".ang.") != -1) || (href.indexOf(".goang.") != -1))
                {
                    s.eVar1 = "Air National Guard";
				}
				
				if((href.indexOf("coastguard") != -1) || (href.indexOf("uscg") != -1))
                {
					s.eVar1 = "Coast Guard";
					if(linkText.indexOf("reserve") != -1)
                    {
                        s.eVar1 += " Reserve";
					}
				}
		
                if(!s.eVar1 || (href.indexOf("google.com") != -1))
                {
					s.eVar1 = "Commercial";
				}
			}
			else
			{
                s.linkTrackEvents="event2";
				s.events = "event2";
				s.eVar1 = "Today's Military";
			}

			  //set eVar3 and corresponding s.prop
			  if(s.eVar1)
			  {
				s.prop6 = s.eVar1;
				s.eVar3 = s.eVar1 + " | " + href.replace(/^https?:\/\//i,"");
			  }
			  
			  //send vals.
			  //var lt = href != null ? s.lt(href) : "";
              //if(lt = "") { s.tl(this,'e'); }
							  

			  //reset the eVars to clean them;
              //s.eVar1 = "";
              //s.eVar3 = "";
            
              window.open(href);
              return false;
								
		}
		else
		{
			
			if($(this).hasClass("iframe"))
			{
				s.linkTrackVars="prop8,events";
				s.events = "event8";
				s.linkTrackEvents="event8";
				s.prop8 = this.id;
				
				s.tl(this,'e');
				
				s.prop8 = "";
			}
		}
});// end
	
	/**
	 * Adds the external link icon to http hrefs - with a  few exceptions
	 * */
	$('a[href^="http"]').each(function(){
			if(this.rel != "entire" && this.rel != "friend" && !$(this).hasClass("iframe"))
			{
				$(this).addClass("external");
			}
	});
	
	$(".iframe").fancybox({
		 
		'overlayShow'	: true,
		'width'		: 430,
		'height'	: 410,
		'overlayOpacity' : .8
		
	});
	
	$(".thickbox,.fancybox").fancybox({
		 
		'overlayShow'	: true,
		'width'		: 700,
		'height'	: 520,
		'autoDimensions' : false,
		'overlayOpacity' : .8
		
		
	});
	
	//bind a click function to the qs tabs
	$("#divQSrchBox > ul > li > a").bind("click" ,function(e){
		core.callback.open_search($(this).text().toLowerCase());
		this.blur();
		return false;
	});
	
	//to toggle the qs box
	$("#h5-qs-toggle").click(function(){
		
		core.toggle_search_box();
	});
    	
	//bind the add to faves function to the add to faves links
	$(".a-add-to-favorites").click(function(){
		var the_url = $(this).attr("href");
		
		// record in omniture that this was added to MyFavorites
		core.handle_add_to_favorites(the_url);
		vars = new Object();
		vars.prop9 = "MyFavorite";
		s.t(vars);
		
		return false;
	});
	
	//bind the remove from faves function to the add to faves links
	$(".a-remove-from-favorites").click(function(){
		var the_rel = "";
		if(this.rel != "" && this.rel != "undefined"){the_rel = this.rel;}
		core.handle_remove_from_favorites($(this).attr("href"), the_rel);
		return false;
	});
	
	//open/close "more filters"
	$("#aMoreF").click(function(){
		
		var add_class = "filter_open";
		var remove_class = "filter_closed";
		
		if( $("#divQSrchBox3").is(":visible")){
			$("#divQSrchBox3").slideUp();
			
			add_class = "filter_closed";
			remove_class = "filter_open";
			
		}
		else{
			$("#divQSrchBox3").slideDown();
			
			add_class = "filter_open";
			remove_class = "filter_closed";
		}
		
		$("#aMoreF").addClass(add_class);
		$("#aMoreF").removeClass(remove_class);
		
		return false;
	})
	
	$(".aShowMore").click(function(){
		var the_name = this.name;
		var cur_text = "Less Details";
		
		$("#"+the_name+"1").toggle();
		$("#"+the_name+"2").toggle();
		
		if($(this).text() == "Less Details"){cur_text = "More Details";}
		
		$(this).text(cur_text);
		
		return false;
		
	});
	
	//setsoff qtips
	$("a.qtip").mouseover(function(){
		$(this).qtip("show");	
	});
	
	//shut off qtip links
	$("a.qtip").click(function(){
		return false;	
	});
	
	//sets up qtip DOM objects
	$("a.qtip").each(function(){
		core.init_qtip(this);
	});
	
	//handles the "expand section" links for the charts (mil and career overviews)
	$("a.chart-expander").click(function(){
		core.handle_chart_expander(this);
		return false;
	});
	
	//handles the ajax submit of the military top list - home page and military section home page
	$("#top-form_military").submit(function(){
		
		var val = $("#slt-ten_military").val();
		var data = "&search-type=industry&is-mil-ten=1&th=Salary&val="+val;
		
		core.basic_ajax("/Ajax/careerTen", data+"&layout=ajax", "html", "#ten-table_military", core.ten_loader);
		return false;
	});
	
	//handles the ajax submit of the schools top list - home page and schools section home page
	$("#ten-form_schools").submit(function(){
		
		var val = $("#slt-ten_schools").val();
		var rotc = core.get_check_box_yes("ss-rotc");
		var type = $("#type-ten").val();
		var major = $("#ss-major").val();
		var data = "&location_search=region&ss-region="+val+"&ss-rotc="+rotc+"&type="+type+"&the-major="+major;
		
		core.basic_ajax("/Ajax/schoolTen", data+"&layout=ajax", "html", "#ten-table_schools", core.ten_loader);
		return false;
	});
	
	$(".open_video_player").click(function(){
		core.open_video_player(this.id);
		return false;
	});
	
	//turn off OOH lins
	$(".job-outlook a").click(function(){
		
		return false;
	});
	
	$("#btn_Qsearch").click(function(){
			//alert($("#quick-search-form").attr("action"));	
	});
	
	//turn off OOH lins
	$(".job-outlook > p >a").click(function(){
		
		return false;
	});


	//resets filters
	$('.clear_filters').live('click', function(){
		alert(location.href);
		window.location = location.href;
		return false;
	});
	
	
});

