var core = {};

core.utilities = {};
core.player = {};
core.commentBox = {};
core.shareStoryForm  = {};


core.utilities.formValuesToJSON = function(formId){
	var data = {};
	$.each($("#" + formId).serializeArray(), function(i, field){
		 if(data[field.name]){
	           if(data[field.name].constructor != Array){
		     data[field.name] = [data[field.name]];
		   }
		   data[field.name].push(field.value);
		 } else {
		   data[field.name] = field.value;
		 }
               });
        return data;
};


core.commentBox.toggle = function(){
	if($("#comment-box-wrapper").css("display") == "none"){
          $("#language").hide();
          $("#comment-box-wrapper").show("fast");
	  $("#comment-box form p:last").addClass("comment-box-state-position");
	  core.commentBox.refresh();
	} else {
          $("#language").show();
	  $("#comment-box-wrapper").css("display", "none");
	}
};

core.commentBox.showThankYou = function(isEsp){
	var thankYouHtml = '<h4>Thank You</h4><a href="#" onclick="core.commentBox.toggle();" id="close-comments">close</a><p class="center">Unfortunately, we cannot reply personally to feedback.</p>';
	if(isEsp){
		thankYouHtml = '<h4>Gracias</h4><a href="#" onclick="core.commentBox.toggle();" id="close-comments">cerrar</a><p class="center">Desafortunadamente, no podemos responder personalmente a su sugerencia.</p>';
	}
	$("#comment-box").html(thankYouHtml);
	core.commentBox.refresh();
        setTimeout('$("#comment-box-wrapper").fadeOut("slow")',3000);
};


core.commentBox.showUserErrors = function(name, errors){
	$("*[@name='"+ name +"']").after((function(){
		return (errors.length > 1)
			? ' <span class="error">' + errors[1] + '</span>'
			: '';
	})());

};

core.commentBox.submitFeedback = function(){

	$("#comment-box span.error").remove();
	$("#comment-submit").attr("disabled", "disabled");
	$("#comment-box #ajax-loader").show();
	var json = core.utilities.formValuesToJSON("feedback-form");
        var langToken = window.location.href.split("lang=");
        var lang = (langToken.length > 1) ? langToken[1] : "eng";
	$.post("/for-parents/feedback/process?lang=" + lang  + "&nocache=" + (new Date()).getTime(), json, null, "script");
	$("#comment-submit").removeAttr("disabled");
	$("#comment-box #ajax-loader").hide();
	return false;
};

core.commentBox.refresh = function(){

	$("#comment-box span.error").remove();
	$("#comment-box #id_feedback").val("");

	sIFR.refresh.commentBoxHeader();

};

core.player.hashRegExp = /.*#(.[^-]*)-?(\d+)?/;

core.player.init = function(clipNav, clipToken){

	if(core.player.isPresent){
		//$("#player a[@href^='#']").click(core.player.process);
		//$("#clip-nav li").click(core.player.process);
		$(".clips li").click(core.player.process);
		$(".player-content:not(:first)").hide();
		if(document.location.hash){
			var re = core.player.hashRegExp.exec(document.location.hash);
			core.player.showActiveClipNav(re[1], re[2] || "0", true);
		} else {
			core.player.showActiveClipNav(clipNav, clipToken, true);
		}
	}

}

core.player.play = function(clipToken){

	document.getElementById("videoPlayer").selectClip(clipToken);

}


core.player.showClip = function(aHref, li, clipToken){


	var re = core.player.hashRegExp.exec(aHref);
	var clipNav = re[1];
	clipToken = re[2];


	core.player.showClipCaptionAndListItem(li, clipToken);
	core.player.showActiveClipNav(clipNav = re[1], clipNav = re[2]);
	core.player.play(clipToken);
	core.player.omnitureTrack(aHref);
};


core.player.showClipCaptionAndListItem = function(liOrAHref, clipToken){
	$("ul.clips li").removeClass("active");

	(typeof liOrAHref == "object")
		? liOrAHref.addClass("active")
		: $("a[@href=" + liOrAHref + "]").parent().addClass("active");
	$(".player-content").hide();
	$("#player-left-panel #player-content-" + clipToken).show();
};



core.player.showActiveClipNav = function(clipNav, clipToken, init){
	$("ul#clip-nav li").removeClass('active');
	$("li#clip-nav-" + clipNav).addClass('active');
	$("ul.clips").hide();
	$("ul#"+ clipNav +"-clips").show();

	if(init){
		setTimeout("core.player.play(" + clipToken + ");", 200);
		core.player.showClipCaptionAndListItem("#" + clipNav+ "-" + clipToken, clipToken);
	} else{
		//document.location = document.location.pathname + "#" + clipNav + "-0";
	}
};

 var nextclip = function(clip){
	 var clipNav = "#veterans";
	 var li = null;
	 var aHref = null;

	 if(clip >=5){
		 clipNav = "#parents";
	 }

	 aHref = clipNav+"-"+clip;
	 li = $("a[@href='" + aHref + "']").parent();

	 core.player.showClip(aHref, li, clip);

 };

core.player.process = function(clipNav, clipToken){


	var a, li;
	clipToken = clipToken || 0;

	if(this.tagName == "LI"){
		li = $(this);
		a = $("a:first", this);
		var href = a.attr("href");
		if(href.indexOf("#") == 0){
			//document.location = document.location.pathname + href;
		}
	} else {
		a = $(this);
		li = a.parent();
	}

	(typeof clipNav == "object")
		? core.player.showClip(a.attr("href"), li, clipToken)
		: core.player.showActiveClipNav(clipNav, clipToken);



};


core.shareStoryForm.init = function(){
	if(core.shareStoryForm.isPresent)
	{
		$("input:not(:first)", $("a#show_more_uploads").parent()).hide();
	}

};

core.player.omnitureTrack = function(href){

		var theUrl = "parents-videos"+href;

		s.linkTrackVars="eVar6,prop6,events";
		s.linkTrackEvents="event4";

		s.events = "event2";
		s.prop6 = theUrl;

		s.tl(this,'c','link_'+theUrl);


};

core.shareStoryForm.showMoreUploads = function(){

  var input = $("input:hidden:first", $("a#show_more_uploads").parent());
	if(input){
		input.addClass("file_upload").show();
		if(input.attr("name") ==  "file_3")
		{
			$("a#show_more_uploads").hide();
		}
	}

};

var playerLoaded = function(){
  setTimeout('core.player.init("parents", 5);', 1000);
};



/* ******************************************************************************** */
// ONLOAD EVENTS
/* ******************************************************************************** */
$(function() {
    
    // Open PDFs in a new window
    $('a').click(function()
    {
        var anchor = $(this);
        if(anchor.attr('href').search(/.pdf$/) != -1)
        {
            anchor.attr('target', '_blank');
        }
    });
    
    /* ******************************************************************************** */
    // OMNITURE
    /* ******************************************************************************** */
    // Gets omniture vars based on string matching for any link that strats with http...
    $('a[href^="http"]').bind("click" ,function(e){
    
        var linkText = $(this).text().toLowerCase();
        var href = $(this).attr("href");
        if(href[href.length-1] == "/") {
            href = href.slice(0,[href.length-1]);
        }
    
        if(href.indexOf("todaysmilitary.com") < 0){ //ensure the tm.com links are not tracked (google searchH)
    
            s.linkTrackVars="eVar1,eVar2,prop2,prop3,events";
            s.linkTrackEvents="event2";
            s.events = "event2";
    
        //set the value for eVar1
        if((linkText.indexOf("army") > -1) || (href.indexOf(".usma.") > -1) || (href.indexOf("goarmy") > -1)){
            s.eVar1 = "Army";
        if(linkText.indexOf("reserve") > -1){
              s.eVar1 += " Reserves";
        }
          }
        if(!s.eVar1 && ((href.indexOf("nationalguard") > -1) || (href.indexOf("goguard") > -1) ||(href.indexOf("ngb.army") > -1) ||(href.indexOf(".ng.mil") > -1))) {
            s.eVar1 = "Army National Guard"
        }  
        if(!s.eVar1 && ((linkText.indexOf("marine") > -1) || (href.indexOf(".usmc.") > -1))){
            s.eVar1 = "Marines";
            if(href.indexOf("Reserves.jsp") > -1)
            s.eVar1 += " Reserve";
        }
        if(!s.eVar1 && ((linkText.indexOf("navy") > -1) || (!s.eVar1 && href.indexOf(".usna.") > -1))){
            s.eVar1 = "Navy";
            if(linkText.indexOf("reserve") > -1) {
                s.eVar1 += " Reserve";
        }
      }
        if(!s.eVar1 && ((linkText.indexOf("force") > -1) || (href.indexOf(".usafa.") > -1) || (href.indexOf("academyadmissions.com") > -1) || (href.indexOf(".dosomethingamazing.com") > -1) || (href.indexOf("afreserve") > -1) || (href.indexOf("af.mil") > -1))){
            s.eVar1 = "Air Force";
            if((linkText.indexOf("reserve") > -1) || (href.indexOf("afreserve") > -1)) {
                s.eVar1 += " Reserve";
            }
        }
        if(!s.eVar1 && href.indexOf(".ang.") > -1){
          s.eVar1 = "Air National Guard";
        }
        if(!s.eVar1 && ((linkText.indexOf("coast") > -1) || (href.indexOf(".uscg.") > -1) || (href.indexOf(".cga.edu") > -1) || (href.indexOf("gocoastguard.com") > -1))){
            s.eVar1 = "Coast Guard";
            if(linkText.indexOf("reserve") > -1){
                s.eVar1 += " Reserve";
        }
      }
      if(!s.eVar1 &&
        (
            (href.indexOf("gibill") > -1)
            || (href.indexOf("asvabprogram.com") > -1)
            || (href.indexOf("commissaries.com") > -1)
            || (href.indexOf("defenselink.mil") > -1)
            || (href.indexOf("dma.mil") > -1)
            || (href.indexOf("dol.gov") > -1)
            || (href.indexOf("gedtest.org") > -1)
            || (href.indexOf("section508.gov") > -1)
            || (href.indexOf("turbotap.org") > -1)
            || (href.indexOf("usuhs.mil") > -1)
            || (href.indexOf("aggiecorps.org") > -1)
            || (href.indexOf("citadel.edu") > -1)
            || (href.indexOf("csum.edu") > -1)
            || (href.indexOf("maritime.edu") > -1)
            || (href.indexOf("norwich.edu") > -1)
            || (href.indexOf("tamug.edu/corps") > -1)
            || (href.indexOf("vmi.edu") > -1)
            || (href.indexOf("vtcc.vt.edu") > -1)
        )
      )
      {
        s.eVar1 = "General Government";
      }
      if(!s.eVar1) {
        s.eVar1 = "General";                                    
      }
    
      //set eVar 2 and corresponding sprop's.
      if(s.eVar1 && s.eVar1 != "General")
      {
        if(((linkText.indexOf("parent") > -1) || (linkText.indexOf(" moms") > -1)) && (href.indexOf("afreserve.com") < 0)){
          s.eVar2 = s.eVar1+" | Parents";
        }
        if(linkText.indexOf("tuition") > -1){
          s.eVar2 = s.eVar1+" | Tuition Information";
        }
        if(linkText.indexOf("recruit") > -1){
          s.eVar2 = s.eVar1+" | Recruiter Information";
        }
        if(linkText.indexOf("news") > -1){
          s.eVar2 = s.eVar1+" | News";
        }
        if(!s.eVar2){
          s.eVar2 = s.eVar1+" | General";
        }
        s.eVar2 +=" | "+href; //append url to eVar2
    
        //set the corresponding sprop's
        s.prop2 = s.eVar1;
        s.prop3 = s.eVar2;
    
      }
      //send vals.
      s.tl(this,'e','link_'+s.eVar1+'_'+href.replace(/^https?:\/\//i,""));
      window.open(href);
    
      //reset the eVars to clean them;
      s.eVar1 = "";
      s.eVar2 = "";
    
    
        }//end tm.com if
        return false;
    });// end
    
    
    // Gets branch interests upon form submission
    $("#btnSubmit").click(function(){
    
        var selectedBranches = "";
    
        //if the corrext form, loop through and get selected vals.
        if($("#fieldsetMIBranches").size() >  0){
            $(".chkBranchInterest").each(function(){
                if(this.checked){
                    selectedBranches += this.value+",";
                }
            });
            
                //set the omniture var
            if(selectedBranches != ""){
                s.linkTrackVars="eVar3";
                s.eVar3 = selectedBranches;
                s.tl(this,'o','"Interested" Form Submissions');
            }
        }
    });//end
        
    /* ******************************************************************************** */
    // END OMNITURE
    /* ******************************************************************************** */

}); 
/* ******************************************************************************** */
// END ONLOAD EVENTS
/* ******************************************************************************** */
