// Initinalization scripts called by onDocumentReady script located in the footer

function initialize(){
	initSifr();
	initializePromoReporting();
	initVideoPlayers();
	initFixForTooltips();
	verticalLineFix();
	navPromoHref();
	topNavRolls();
}

function verticalLineFix(){
	var $h = $("#tier_2").height();
	$("#tier_2 .vertical_line").height(($h-5));
}

function submitSite(base,field,form) {
	form.action = base + "?term=" + form[field].value;
	form.target = "_self";

	if((form[field].value == "")||(form[field].value == "Search")){
		alert("Please enter a search term");
		return false;
	}else{
		form.submit();
	}
}

function submitZIPsearch(base,field,form) {
	//form.action = base + "?term=" + form[field].value;
	//form.target = "_self";

	if (validateZIP(form[field].value)) {
		$('.channel_finder .error_text').hide();
		form.submit();
		return true;
	} else {
		$('.channel_finder .error_text').html("Please enter a valid 5-digit zip code.");
		$('.channel_finder .error_text').show();
		return false;
	}
}

function submitWeb(field,form) {
	form.action = "http://www.live.com";
	form.target = "_blank";

	var q_input = document.createElement('input');
	q_input.setAttribute("type", "hidden");
	q_input.setAttribute("name", "q");
	q_input.setAttribute("value", form[field].value);
	form.appendChild(q_input);

	if((form[field].value == "")||(form[field].value == "Search")){
		alert("Please enter a search term");
		form.removeChild(q_input);
		return false;
	}

	else{
		form.submit();
		form.removeChild(q_input);
		return false;
	}
}

/**** sIFR ***/
function initSifr(){
//TODO: fix path
//	$.sifr({path:"/sitewide/flash/sifr/",save:true});
//	$(".header_30").sifr({font:"avantgarde demi.swf"})
//	$(".header_24").sifr({font:"avantgarde demi.swf"})
//	$(".header_18").sifr({font:"avantgarde demi.swf"})
}


function toggleDisplay(which) {
	$(which).toggle();
}

function validateEmail(emaillAddress) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var address = emaillAddress;
	return reg.test(address);
}

function validatePhone(phoneNumber){
	var pat = "^";
	var exp;
	pat =  "(\\(?\\d{3}\\)?([-. ])?)?\\d{3}([-. ])?\\d{4}\\s?(\\-|x|X|ext|EXT|ex|EX| )?\\s?\\d{0,6}?$";
	exp = new RegExp(pat);
	return exp.test(phoneNumber);
}

function validateDOB(dob) {
	var reg = /^([0-9]{2})+\/([0-9]{2})+\/([0-9]{2})$/;
	var dateofbirth = dob;
	return reg.test(dateofbirth);
}

function validateZIP(zip) {
	var reg = /^([0-9]{5})$/;
	var zipcode = zip;
	return reg.test(zipcode);
}

//$(document).ready callback.
function initializePromoReporting(){
	var promo_pat = /mod_(\w*)/,
	pageName = 'unset';

	// Try to get the page name. If this fails, the user probably has ad block enabled.
	try{
		pageName = mtvn.btg.reporting.ReportingManager.getData().pageName ? mtvn.btg.reporting.ReportingManager.getData().pageName : 'not-reported';
	}catch (e){
		pageName = 'failed';
	}

	$('#top_nav area').each(function (){
		$(this).click(function (){
			com.mtvi.reporting.Controller.sendLinkEvent({
				linkName:'top-nav ' + pageName,
				linkType:'o',
				eVar7:'top-nav',
				prop25:'top-nav',
				eVar8:'top-nav ' + pageName,
				prop26:'top-nav '+pageName,
				eVar9:pageName
			});
		});
	});

	$('[id*="mod_"] a').each(function (){
		var promo_names = [],
		parent_mods = $(this).parents('[id*="mod_"]:first'),
		link_name = '';

		parent_mods.each(function (){
			var matches = promo_pat.exec($(this).attr('id'));
			if (matches && matches[1]){
				link_name = matches[1];
			}
		});

		$(this).click(function (){
			com.mtvi.reporting.Controller.sendLinkEvent({
				linkName:link_name + '|' + pageName,
				linkType:'o',
				eVar7:link_name,
				prop25:link_name,
				eVar8:link_name + '|' + pageName,
				prop26:link_name + '|'+pageName,
				eVar9:pageName
			});
		});
	});
}

function initVideoPlayers(){

        $('.video_entry').each(function(){
            return new VideoEntry(this);
        });
        $('.video_list').each(function(){
            return new VideoListBox(this);
        });
        if ($('.tvland_share')) {
        	$('.tvland_share').each(function() {
        		if ($(this).attr("videoTitle") && $(this).attr("videoTitle") != "") {
        			var title = $(this).attr("videoTitle");
        			var url = $(this).attr("url");
        			var embed = $(this).attr("embed");
        			var type = $(this).attr("type");
        			return new TVLandShareThis($(this), url, title, embed, type);
        		}
        	});
        }
		
        
	$('.playlistPromo .video_entry_tooltips .video_entry_tooltip').each(function(){
		//
		// DOM nodes.
		//
			var $tooltip = $(this),
		$tooltip_window = $tooltip.parent(),
		$tooltip_arrow = $tooltip.find('.arrow'),
		index = $tooltip.attr('id').replace('video_entry_tooltip_', ''),
		$entry = $('#video_entryContainer_' + index),
		//
		// Static math.
		//
		tooltip_window_height = $tooltip_window.height(),
		// This starts off null because we can't calculate it until it's made
		// visible with a user roll over.
		tooltip_height = null,
		tooltip_arrow_height = null,
		entry_height = $entry.height(),
		video_list_height = $entry.parent().height(),
		tooltip_top_offset = parseInt((tooltip_window_height - video_list_height)/2);
		tooltip_top_offset=0;
		
		indent = $('#t2_lc').position().left + 225;

		
		$tooltip_window.css('left', indent);
		
		
		$entry.mouseenter(function (event){
			var entry_top = $entry.position().top,
			entry_middle = parseInt(entry_top - entry_height/2),
			tooltip_top = null,
			tooltip_arrow_top = null;

			$tooltip_window.css('display', 'block');
			$tooltip.addClass('tooltip-selected');

			// Must come after the preceding class changes because the node must be
			// visible before calculating the height.
			if (tooltip_height == null){
				tooltip_height = $tooltip.height();
				tooltip_arrow_height = $tooltip_arrow.height();
			}

			// Out of bounds corrections.
			tooltip_top = parseInt(entry_top - (tooltip_height - entry_height) / 2 + tooltip_top_offset);
			tooltip_arrow_top = parseInt((tooltip_height - tooltip_arrow_height) / 2);
			if (tooltip_top < 0){
				// We're shifting the tooltip down, so we need to shift the arrow up
				// (tooltip_top is currently negative).
				tooltip_arrow_top = parseInt(tooltip_arrow_top + tooltip_top);
				tooltip_top = 0;
			} else if (tooltip_top + tooltip_height > tooltip_window_height){
				// We're shifting the tooltip up, so we need to shift the arrow down.
				tooltip_arrow_top = parseInt(tooltip_arrow_top + (tooltip_top - (tooltip_window_height - tooltip_height)));
				tooltip_top = parseInt(tooltip_window_height - tooltip_height);
			}

			$tooltip.css('top', tooltip_top + 'px');
			$tooltip_arrow.css('top', tooltip_arrow_top + 'px');
		});

		$entry.mouseleave(function (event){
			$tooltip.removeClass('tooltip-selected');
			$tooltip_window.css('display', 'none');
		});
	});
}

function initFixForTooltips(){
	$('.tease .tvl_off').mousemove(function(e){
		var _obj = $(this).find('.tooltip');
		$(this).find('.tooltip').css({left:e.pageX - $(this).offset().left + 10, top:e.pageY - $(this).offset().top - 47});
		$(this).find('.tooltip.reflectedTooltip').css({left:e.pageX - $(this).offset().left - _obj.width() - 10, top:e.pageY - $(this).offset().top - 47});
		if ( !(e.pageX >= $(this).offset().left &&
			e.pageX <= $(this).offset().left + $(this).width() &&
			e.pageY >= $(this).offset().top &&
			e.pageY <= $(this).offset().top + $(this).height()) )
		{
			$(this).find('.tooltip').css('display','none');
			var _obj = this;
			setTimeout(function(){ $(_obj).find('.tooltip').removeAttr('style'); }, 10);
		}
	});
}

function set_equal_height(columns){
	var tallestcolumn = 0;
	columns.css("height", "auto").each(
		function(){
			currentHeight = $(this).height();
			if(currentHeight > tallestcolumn){
				tallestcolumn = currentHeight;
			}
		}
	);
	columns.height(tallestcolumn);
}

function navPromoHref(){
	$("#nav_promo_href").attr("href",$("#top_navigation .ad .basic a").attr("href"));
}

function topNavRolls(){
    $("#top_nav > *").mouseover(function () {
	  $(".nav_holder").addClass($(this).attr("class"));
    }); 
	$("#top_nav > *").mouseout(function () {
		$(".nav_holder").removeClass($(this).attr("class"));
	});   
  }







