/*********************************************************************************
Authors : 		Jade Rauzenbaum and Martin Halla
Description : 	The JS and jQuery functions for foxnewsaffiliates.com website
Created : 		Spring 08
Last Update : 	11/22/08
*********************************************************************************/

$(document).ready(function() {

	/**
		This function collects the select boxes values and rettrives the amount
		of the emails via ajax call , then it updates the dom element
	**/
	function get_emails_count() {
		var dep_id = $("#FilterDepartments").val();
		if(dep_id=="undefined" || dep_id == "" || dep_id == null) dep_id = 0;
		
		var aff_id = $("#FilterAffiliations").val();
		if(aff_id=="undefined" || aff_id == "" || aff_id == null) aff_id = 0;
		
		var com_id = $("#FilterCompanies").val();
		if(com_id=="undefined" || com_id == "" || com_id == null) com_id = 0;
		
		var url = "/bulk_emails/ajax_get_emails_count/" + dep_id + "/" + aff_id+ "/" +com_id;
		$("#filter_amount").load(url);
		//alert(url);
	}
	$("#filter_amount").change(function() {alert("I changed !");});
	
	$("#btn_test").click(function()
		{
			$("#btn_test").load("/bulk_emails/test");
		}
	);
	
	$("#FilterDepartments").change(function()	
		{
			get_emails_count();
		}
	);
	
	$("#FilterCompanies").change(function()	
		{
			get_emails_count();
		}
	);
	
	$("#FilterAffiliations").change(function()	
		{
			get_emails_count();
		}
	);
	
	// round corners
	if($('.contentBox').length != 0) { $('.contentBox').corner('7px'); }
	if($('.program').length != 0) { $('.program').corner('7px'); }
	if($('.affilateContent').length != 0) { $('.affilateContent').corner('7px'); }
	if($('.affiliateContentFull').length != 0) { $('.affiliateContentFull').corner('7px'); }
	if($('.registerBox').length != 0) { $('.registerBox').corner('7px'); }

	// table sorting
	if($('#assetForm').length != 0) { $("#assetForm").tablesorter(); }
	
	
	// placing 'default' values into month/year - b/c cake's api is way too limited and I don't
	// want to rewrite their HTML helper
	if($('#SearchSearchMonth').length != 0) {
		$('#SearchSearchMonth > option:eq(0)').html('-Month-');
	}
	if($('#SearchSearchYear').length != 0) {
		$('#SearchSearchYear > option:eq(0)').html('-Year-');
	}
	
	// removing / readding 'Search by keyword' default txt
	if($('#SearchSearchKeywords').length != 0) {
		$('#SearchSearchKeywords').click(function() {
			if($(this).attr('value') == 'Search by keyword') {
				$(this).attr('value','').css('color','#000000');
			}
		});
		$('#SearchSearchKeywords').blur(function() {
			if(!$(this).attr('value')) {
				$(this).attr('value','Search by keyword').css('color','#929292');
			}
		});
	}
	
	// turning on / off registration form fields on select of the checkbox
	if($('.foxCheck').length != 0) {
		
		
		
		// onload:: have to hardset IDs b/c id isn't passing for some reason...
		if($('#foxNewsForm').attr('checked')) {
			$('#foxNewsFormBox').css('display','block');
		}
		if($('#foxBizForm').attr('checked')) {
			$('#foxBizFormBox').css('display','block');
		}
		
		// click functions
		$('.foxCheck').click(function() { // click works in both IE6 and FF, was change before
			var boxID = $(this).attr('id')+'Box';
			if(this.checked) {
				$('#'+boxID).slideDown();
			} else {
				$('#'+boxID).slideUp();
			}
		});
		
		

		
	}
	
	// subnav self-detecting
	if($('.subnav ul').length != 0) { activateNav('.subnav ul'); }

	// placing us flash map
	if($('#flashMap').length != 0) {
		var flashMap = new SWFObject("/swfmap/us_map.swf", "mymovie", "530", "410", "8", "#ffffff");
		flashMap.addVariable("xmlfile1", "/swfmap/us_data.xml");
		flashMap.addParam('wmode','transparent');
		flashMap.write("flashMap");
	}

	// hover effect on affiliate details
	if($('.affiliateDetails').length != 0) {
		$('.affiliateDetails').hover(function() {
			$(this).toggleClass('hover');
			$(this).corner('5px');
		},
		function() {
			$(this).toggleClass('hover');
		});
	}
		
	// Video player
	loadplayer();
	
	
	// multUpload
	if($('.upload').length != 0) {
		$('.upload').MultiFile({
			accept:'gif|jpg|png|pdf', max:5, STRING: {
				remove:'Remove',
				selected:'Selected: $file',
				denied:'Invalid type $ext!'
			}
		});
	}
	
	// js waiting/disabling for bulk emails... since it takes forever
	if($('#send_bulk_message').length != 0) {
		$('#send_bulk_message').submit(function() {
			$('.bulkLoad').css({display: 'inline'});
			$('.bulkLoad input').attr('disabled','disabled');
		})
	} 
	
	// this is for the  sweeepstakes sign up for Fox and Friends
	if($('#total_subs').length != 0) {
		$('#total_subs').blur(function() {
		
		  
			var value = ($('#total_subs').val());
			if(is_numeric(value)) {
				value = addSeparatorsNF(value,'.','.',',');
				$('#total_subs').val(value);
			}else {
				alert("Please provide a numeric value for Total Subscribers");
				$('#total_subs').focus();
			}
		});
	
	
	}
	
	
	load_sweepstakes();
	if($('.form_error').length !=0 &&  $('.imus-sweep').length != 0 ){
		$('.imus-errors-section')
			.prepend("<p>* Please fill in required fields</p>")
			.css("background-color","#FFCCCC");
		if($("#telephone").attr("value") != undefined ) $("#telephone").attr("value",$("#telephone").attr("value").slice(0,$("#telephone").attr("value").indexOf("x")) );
	}	
	/*if( (
			jQuery('#contact').attr("value") != undefined ||
			jQuery('#title').attr("value") != undefined ||
			jQuery('#system').attr("value") != undefined ||
			jQuery('#dma').attr("value") != undefined ||
			jQuery('#address').attr("value") != undefined ||
			jQuery('#city').attr("value") != undefined ||
			jQuery('#zip').attr("value") != undefined ||
			jQuery('#telephone').attr("value") != undefined ||
			jQuery('#email').attr("value") != undefined ||
			jQuery('#total_subs').attr("value") != undefined
		) &&
			jQuery("#onair_onair").attr('checked') == undefined &&
			jQuery("#onair_sweepstakes").attr('checked') == undefined &&
			jQuery('.imus-sweep').length != 0){
				jQuery('.imus-errors-section')
				.prepend("<p>* Please Choose On-Air Sponsorship Or Sweepstakes Sponsorship</p>")
				.css("background-color","#FFCCCC");
				if($("#telephone").attr("value") != undefined ) $("#telephone").attr("value",$("#telephone").attr("value").slice(0,$("#telephone").attr("value").indexOf("x")) );
	}*/
	var fncWegnerHTML = jQuery('#HRDOldFncWegnerNumber').parent().parent().html();
	var fbnWegnerHTML = jQuery('#HRDOldFbnWegnerNumber').parent().parent().html();
	var fncMotorolaHTML = jQuery('#HRDNewFbnWegnerNumber').parent().parent().html();
	var fbnMotorolaHTML = jQuery('#HRDNewFbnWegnerNumber').parent().parent().html();
	$('#HRDServiceLaunching').change(function(){
		   $("select option:selected").each(function() {
		               var value = $(this).text();
		                switch(value){
		                case "FNC HD":
		                  $('#HRDOldFncWegnerNumber').parent().css({'display' : 'block'});
		                  $('#HRDOldFncWegnerNumber').parent().prev().css({'display' : 'block'});
		                  $('#HRDNewFncMotorolaNumber').parent().css({'display' : 'block'});
		                  $('#HRDNewFncMotorolaNumber').parent().prev().css({'display' : 'block'});
		                  
		                  $('#HRDChannelFnc').parent().css({'display' : 'block'});
		                  $('#HRDChannelFnc').parent().prev().css({'display' : 'block'});
		                  $('#HRDChannelFbn').parent().css({'display' : 'none'});
		                  $('#HRDChannelFbn').parent().prev().css({'display' : 'none'});
		                  
		                  $('#HRDOldFbnWegnerNumber').val(0);
		                  $('#HRDNewFbnMotorolaNumber').val(0);
		                  $('#HRDOldFncWegnerNumber').val("");
		                  $('#HRDNewFncMotorolaNumber').val("");
		                  $('#HRDChannelFnc').val("");
		                  $('#HRDChannelFbn').val(0);
		                  
		                  
		                  $('#HRDOldFbnWegnerNumber').parent().css({'display' : 'none'});
		                  $('#HRDOldFbnWegnerNumber').parent().prev().css({'display' : 'none'});
		                  $('#HRDNewFbnMotorolaNumber').parent().css({'display' : 'none'});
		                  $('#HRDNewFbnMotorolaNumber').parent().prev().css({'display' : 'none'});
		                break;
		                case "FBN HD":
		                  $('#HRDOldFbnWegnerNumber').parent().css({'display' : 'block'});
		                  $('#HRDOldFbnWegnerNumber').parent().prev().css({'display' : 'block'});
		                  $('#HRDNewFbnMotorolaNumber').parent().css({'display' : 'block'});
		                  $('#HRDNewFbnMotorolaNumber').parent().prev().css({'display' : 'block'});
		                  
		                  $('#HRDChannelFnc').parent().css({'display' : 'none'});
		                  $('#HRDChannelFnc').parent().prev().css({'display' : 'none'});
		                  $('#HRDChannelFbn').parent().css({'display' : 'block'});
		                  $('#HRDChannelFbn').parent().prev().css({'display' : 'block'});
		                  
		                  $('#HRDOldFncWegnerNumber').val(0);
		                  $('#HRDNewFncMotorolaNumber').val(0);
		                  $('#HRDOldFbnWegnerNumber').val("");
		                  $('#HRDNewFbnMotorolaNumber').val("");
		                  $('#HRDChannelFnc').val(0);
		                  $('#HRDChannelFbn').val("");
		                  
		                  
		                  $('#HRDOldFncWegnerNumber').parent().css({'display' : 'none'});
		                  $('#HRDOldFncWegnerNumber').parent().prev().css({'display' : 'none'});
		                  $('#HRDNewFncMotorolaNumber').parent().css({'display' : 'none'});
		                  $('#HRDNewFncMotorolaNumber').parent().prev().css({'display' : 'none'});
		                break;//FNC HD &amp; FBN HD
		                case "FNC HD & FBN HD":
		                  $('#HRDOldFncWegnerNumber').parent().css({'display' : 'block'});
		                  $('#HRDOldFncWegnerNumber').parent().prev().css({'display' : 'block'});
		                  $('#HRDNewFncMotorolaNumber').parent().css({'display' : 'block'});
		                  $('#HRDNewFncMotorolaNumber').parent().prev().css({'display' : 'block'});
		                  
		                  $('#HRDChannelFnc').parent().css({'display' : 'block'});
		                  $('#HRDChannelFnc').parent().prev().css({'display' : 'block'});
		                  $('#HRDChannelFbn').parent().css({'display' : 'block'});
		                  $('#HRDChannelFbn').parent().prev().css({'display' : 'block'});
		                  
		                  $('#HRDOldFncWegnerNumber').val("");
		                  $('#HRDNewFncMotorolaNumber').val("");
		                  $('#HRDOldFbnWegnerNumber').val("");
		                  $('#HRDNewFbnMotorolaNumber').val("");
		                  $('#HRDChannelFnc').val("");
		                  $('#HRDChannelFbn').val("");
		                  
		                  $('#HRDOldFbnWegnerNumber').parent().css({'display' : 'block'});
		                  $('#HRDOldFbnWegnerNumber').parent().prev().css({'display' : 'block'});
		                  $('#HRDNewFbnMotorolaNumber').parent().css({'display' : 'block'});
		                  $('#HRDNewFbnMotorolaNumber').parent().prev().css({'display' : 'block'});
		                break;
		           }
		                                     
		               
		   });
		           
		         
		 
		});
}); // END OF DOC READY

// #########################
// Site Functions
// #########################

function get_subdomain() {
	// plit the url into an array
	var href= window.location.href.split(".");
	// get the first part
	var subdomain = (href[0]);
	// get rid of http://
	subdomain = subdomain.substring(7,(subdomain.length));
	//alert(subdomain);
	return subdomain;
}

function activateNav(nav) {
	// split url and get page (or lack of page - index)
	var url = document.location.href.split('/');
	var section = url[3];

	// if we're in a non-index (section index wouldn't have a subsection)
	if(url[4]) {
		var subSection = url[4];
		$(nav+' a[href*='+subSection+']').parent().addClass('active');

		// we're getting fancy here - li before active needs special class too
		$(nav+' a[href*='+subSection+']').parent().prev().addClass('beforeActive');
	}
	// else - put slightly altered active on the first one
	else {
		$(nav+' li:first-child').addClass('active');
		$(nav+' li:first-child').addClass('firstActive');
	}
}

function getState(state,st) {
	$.ajax({
		type: "POST",
		url: "/generalInfo/getState/"+st,
		success: function(response) {
			$('.affilateContentArea').html(response);
			$('.affiliateInfo h2').html(state);
		}
	});
}

function editBox(url,selectID,viewURL,layoutDepreiated) {
	
	// set function vars
	var fillAjax = false;
	var boxName = selectID+'Box';
	var layout = $('.layout').html();
	
	//######alert(boxName);
	// close all admin controls that are potentially open
	if($('.adminEditBox:visible').length > 0) {
		updatePage(viewURL);
		$('.adminEditBox').fadeOut('slow');
	}
	
	
	// NEW: ALWAYS CREATING b/c div gets destroyed on close.
	// leaving filter on for error security....
	if($('#'+boxName).length == 0) {
		//alert(1);
		// create popover
		var the_html ='<div id="'+boxName+'" class="adminEditBox"><div><img src="/img/ajax-loader.gif" alt="Loading..." /></div></div>';
		//alert(the_html);
		$('.container').after(the_html);
		//alert(2);
		$.ajax({
			type: 'POST',
			url: url,
			success: function(response) {
				$('#'+boxName+' div').html(response);
				// fillAjax needs to be reset for some reason
				fillAjax = false;
			}
		});
	}
	
	
	// check div visibility / toggle
	if($('#'+boxName).css('display') == 'none') {
		// show div
		$('#'+boxName).fadeIn('slow');
		createMask(selectID,viewURL);
		
		// new: hide any flash items if they exist
		if($('#flashMap').length != 0) { $('#flashMap').css({visibility: 'hidden'}); }
		if($('#vidPlayer').length != 0) { $('#vidPlayer').css({visibility: 'hidden'}); }
	}
}









function editRecords(editID) {
	var editForm = '#'+editID+'Box form';
	var editDiv = '#'+editID+'Box div';

	// submit tinyMCE to take text out of iframe and put back in textarea
	tinyMCE.triggerSave();
	
	// NEW: using jQuery's ajax submit plugin - helps with image uploads
	$(editForm).ajaxSubmit({
		url: $(editForm).attr('action'),
		success: function(response) {
			$(editDiv).html(response);
		}
	});
}



// fades out and removes admin components from view 
function closeEdit(selectID,url,layoutDepreciated) {
	var selectBox = '#'+selectID+'Box';
	
	$(selectBox+', #popMask').fadeOut('slow',function() {
		$(this).remove();
	});
	
	// new: display any flash maps that were hidden
	if($('#flashMap').length != 0) { $('#flashMap').css({visibility: 'visible'}); }
	if($('#vidPlayer').length != 0) { $('#vidPlayer').css({visibility: 'visible'}); }
	updatePage(url);
	loadplayer();
}

//load videoplayer
function loadplayer() {
	if($('#vidPlayer').length != 0) {
		var vidPlayer = new SWFObject("/video/player_v416.swf", "videoPlayer", "300", "200", "8", "#6699CC");
		vidPlayer.addParam('allowscriptaccess','always');
	  	vidPlayer.addParam('allowfullscreen','true');
	  	vidPlayer.addParam('autostart','false');
	  	/* Default movie and picture */
	  	
	  	var image = "/video/fox-news-logo.jpg";
	  	// get the subdomain name and if it is foxbiz , change the logo image
	  	if(get_subdomain()=="foxbiz") image ="/video/fox-biz-logo.jpg"
	  	vidPlayer.addParam('flashvars','&file=/video/20051210-w50s_56K.flv&image=' + image);
	  	vidPlayer.addVariable('javascriptid','videoPlayer');
	  	vidPlayer.addVariable('enablejs','true');
	  	//vidPlayer.addVariable("linktarget", "_self");
		vidPlayer.write("vidPlayer");
	}
}
function playerReady(thePlayer) {
	vidPlayer = document.getElementById(thePlayer.id);
	addListeners();
}
function addListeners() {
	if (vidPlayer) { 
		vidPlayer.addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners()",100);
	}
}
function stateListener(obj){
	if(obj.newstate =="COMPLETED"){	
		vidPlayer.sendEvent("STOP",null);
	}
}



function updatePage(url,layoutDepreciated) {
	var layout = $('.layout').html();
	
	
	// NEW: Sweepstakes gets updated in a totally different area
	// Override settings for sweepstakes
	if(url == 'sweepstakes') {
		url = '/home/sweepstakes/true';
		
		//url = '/home/get_sweepstakes/true';
    layout = 'sweepstakes';
	}
	if (url=='/marketingMaterials/cross_channel_promos/true' || url=='/sweepstakes/ajax_view' || url=='/marketing_materials/cross_channel_promos/true') {
		layout = 'showplayer';
	}
	
	$.ajax({
		type: 'POST',
		url: url,
		success: function(response) {
			if(layout == 'home') {
				$('.homeContent').html(response);
			} else if(layout == 'login') {
				$('.loginContent').html(response);
			} else if(layout == 'nobox') {
				$('.pageContent').html(response);
			} else if(layout == 'sweepstakes') {
				$('.callout').html(response);
			}else if (layout=='showplayer') {
				$('.contentBox > div').html(response);
				loadplayer();
      } else {
				$('.contentBox > div').html(response);
			}
		}
	});
}

function createMask(selectID,url,layoutDepreciated) {
	if($('#popMask').length == 0) {
		$('<div id="popMask" style="height: '+$(document).height()+'px;" onclick="closeEdit(\''+selectID+'\',\''+url+'\');"></div>').appendTo('body').fadeIn();
	} else {
		$('#popMask').fadeIn();
	}
}

function fadeStatus() {
	$('.popStatus').fadeOut('slow');
}

function loadMCE() {
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		plugins : "safari,pagebreak,iespell,searchreplace,contextmenu,paste,directionality,visualchars,nonbreaking,template",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "bottom",
		theme_advanced_toolbar_align : "center",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
		template_external_list_url : "example_template_list.js"
	});
}

// #########################
// jw player JS
// #########################
function sendEvent(swf,typ,prm) { 
	thisMovie(swf).sendEvent(typ,prm); 
};
function getUpdate(typ,pr1,pr2,swf) {};
function thisMovie(swf) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[swf];
	} else {
		return document[swf];
	}
};
function loadFile(swf,obj) { 
	thisMovie(swf).loadFile(obj);
};

/***********************************************
 new function for the JW player version 416 
************************************************/

function stop_movie() {
	player = document.getElementById("videoPlayer");
	player.sendEvent("STOP",null);
}

function play_movie(id,url) {
	player = document.getElementById(id);
	
	var obj = {file:url};
	player.sendEvent("LOAD",obj);
	player.sendEvent("PLAY",true);
	
}


function load_sweepstakes() {
	$("#sweepstakes_box").load("/sweepstakes/ajax_view");
}

//fades out and removes admin components from view 
function sweepstakes_closeEdit(selectID,url,layoutDepreciated) {
	var selectBox = '#'+selectID+'Box';
	if($('#flashMap').length != 0) { $('#flashMap').css({visibility: 'visible'}); }
	if($('#vidPlayer').length != 0) { $('#vidPlayer').css({visibility: 'visible'}); }
	$(selectBox+', #popMask').fadeOut('slow',function() {
		$(this).remove();
	});
	$.ajax({
		type: 'GET',
		url: '/sweepstakes/ajax_view',
		success: function(response) {
			$('.callout').html(response);
		}
	});
}



/* Format number */
function addSeparatorsNF(nStr, inD, outD, sep)
{
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}



function is_numeric(sText)

{
   var ValidChars = "0123456789.,";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
   
   
 	/**
	 * This is for the program info time zone updades 
	 * Created by Martin Halla (martin@halladesign.com ) on February 12th for  Fox News  Channel
	 */
	  
	//if($("#program_info_updated").length!=0) {
			function do_change_time_zone() {
				
				// get the select_object
				var select_obj = document.getElementById("change_time_zone");
				var val = select_obj.options[select_obj.selectedIndex].value
				
				// make the URL
				var url = "/program_info/index/1/"+val;
				
				// load the url and selected div into the div ...
				$("#program_info_updated").load(url + " #program_info_updated");
				
			}
	//}  

