window.onerror = function() {
	return true; // prevents browser error messages
};

// $(document).ready callback.
function docready(){
	initPromoTracking();
}

//Auto Link, Top Nav, & All Other sendLinkEvent Click Function
function autoLinkTrackEvent(promoName, destinationUrl){
	var destinationUrl = (typeof destinationUrl != 'undefined') ? destinationUrl : 'no_destination_url';

	mtvn.btg.Controller.sendLinkEvent({
		linkName:promoName + '|' + pageName,
		linkType:'o',
		prop25:promoName,
		prop26:promoName + '|' + pageName,
		prop27:destinationUrl,
		eVar5:destinationUrl,
		eVar7:promoName,
		eVar8:promoName + '|' + pageName,
		eVar9:pageName
	});
}

function initPromoTracking() {
	
	// Top nav links	
	$('.top-nav a').click(function (){
		var destinationUrl = $(this).attr('href');
		autoLinkTrackEvent('top-nav', destinationUrl);
	});
	
	$('.ccLogoBarInner a').click(function (){
		autoLinkTrackEvent('cclogo', $(this).attr('href'));
	});	
	
	$('.scheduleLinks a').click(function (){
		autoLinkTrackEvent('schedule', $(this).attr('href'));
	});	
	
	$('.followUs a').click(function (){
		autoLinkTrackEvent('socialbuttons', $(this).attr('href'));
	});	
	
	$('.fanactivity a').click(function (){
		autoLinkTrackEvent('fanactivity', $(this).attr('href'));
	});	
	
	
	$('.tweetText a').click(function (){
		autoLinkTrackEvent('fanactivity', $(this).attr('href'));
	});
	
	$('.fbRecommendationWidgetContent a').click(function (){
		autoLinkTrackEvent('fanactivity', $(this).attr('href'));
	});
	
	// Search Box
	$('.ms_search_button_site_cc').click(function (){
		var destinationUrl = $(this).closest('form').attr('action');
		autoLinkTrackEvent('searchbox', destinationUrl);
	});
	
	// Channel Finder Module
	$('#zccSubmit').click(function (){
		var destinationUrl = $(this).closest('form').attr('action');
		autoLinkTrackEvent('channelfinder', destinationUrl);
	});
	
	$('#cc_footer a').click(function (){
		autoLinkTrackEvent('footer', $(this).attr('href'));
	});
	
	// Email Links
    $("a.email").click(function() {
    	autoLinkTrackEvent('newsletter', $(this).attr('href'));
    });
    
	// All other General Modules auto link tracking
	var $allModuleATags = $('div.[class*="mod_"] a'); // Get <a> tags with <div>s that have "module" in the name
	
	$($allModuleATags).each(function (){
		
		// Get the Div that contains the <a> tag
		$divWithModuleClass = $(this).closest('div.[class*="mod_"]'); // Get <div> that is closest to the <a> tag with module in class name
		var destinationUrl = $(this).attr('href');
		
		var matches;
		var promo_name = 'unnamed_promo'; // protect against no second class name
		var allClasses = $divWithModuleClass.attr('class'); // classes of div as a string
	
		// make sure its not an ad slot && auto tracking is wanted
		skipTheseClasses = /(noAutoLinkTracking|ad_)/;
		if ( !skipTheseClasses.test(allClasses) ){
			
		    var promo_pat = /mod_(\w*)/;
			
			// Determine Promo Name			

			// All divs with class named module
			var promo_pat = /mod_([\w-]+)/i; // General Auto Link Pattern for class list
			
			var matches = promo_pat.exec(allClasses);
			if ( (typeof matches != 'undefined') && (typeof matches[1] != 'undefined') ){
				promo_name = matches[1]; // matched pattern (1) from regEx
			} else {
				promo_name = 'module';
			}
	
			$(this).click(function (){
				autoLinkTrackEvent(promo_name, $(this).attr('href'));
			});
		}
	});
}

function ccPopWindow(pgVars){
	var popUrl = pgVars.url;
	var windowName;
	var windowAttributes;
	windowName = (pgVars.windowName === "" || pgVars.windowName === "undefined") ? "cc_pop_window" : pgVars.windowName;
	windowAttributes = (pgVars.windowAttributes === "" || pgVars.windowAttributes === "undefined") ? "" : pgVars.windowAttributes;
	var poppedWindow = window.open(popUrl,windowName,windowAttributes);
}

function addLoadEvent(func){
	try{
    	if(window.attachEvent){window.attachEvent("onload",func);}
        if(window.addEventListener){window.addEventListener("load",func,false);}
        return this;
    }catch(e){}
}
/* Converts first letter of every word to upper case */
function changeEveryFirstLetterToCap (stringToConvert){
	var lowerCaseString = stringToConvert;
	var upperCaseString = "";
	var ch;       // One of the characters in str.
	var prevCh = '';   // The character that comes before ch in the string.
	var i;         // A position in str, from 0 to str.length()-1.
	for ( i = 0;  i < lowerCaseString.length;  i++ ) {
		ch = lowerCaseString.charAt(i).toLowerCase();
		if ( (ch!=' ')  &&  ( (prevCh==' ') || (prevCh=='') )) upperCaseString+=ch.toUpperCase();
		else upperCaseString+=ch;
		prevCh = ch;
	}
	return upperCaseString;
}
/* mimics java's URLEncode */
function URLencode(urlToEncode){
  return escape(urlToEncode).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
}
/* START: Cookie Functions */
function setCookie(name,value,days){
	if (days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}//end if
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function deleteCookie(name){
	setCookie(name,"",-1);
}
/* END: Cookie Functions */

/* div manipulation */
function changeDivStyle(divId,styleToChange,styleValue){
	//alert("changeDivStyle:\nDiv ID: " +divId +"\nStyle To Change: "+styleToChange +"\nStyle Value: "+styleValue);
	if (document.getElementById(divId)){
		var theDiv = document.getElementById(divId);
		if (styleToChange=="src") theDiv.src = styleValue;
		else theDiv.style[styleToChange] = styleValue;
	}
}
function ccHttpRequest(url, parameters, successFunction) {
	var cc_http_request = false;
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari,...
		cc_http_request = new XMLHttpRequest();
		if (cc_http_request.overrideMimeType)
		{
			cc_http_request.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject)
	{ // IE
		try {
			cc_http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				cc_http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!cc_http_request) {
		//alert('Cannot create XMLHTTP instance');
		return false;
	}

	cc_http_request.onreadystatechange = function(){
		if (cc_http_request.readyState == 4) {
			if (cc_http_request.status == 200){
				eval(successFunction);
			}
			//else alert("xml status error: " + cc_http_request.statusText);
		}
	};
	cc_http_request.open('POST', url, true);
	cc_http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	cc_http_request.setRequestHeader("Content-length", parameters.length);
	cc_http_request.setRequestHeader("Connection", "close");
	cc_http_request.send(parameters);
}

function truncateText(id,length){
	var len = length;
	var p = document.getElementById(id);
	if (p) {
		var trunc = p.innerHTML;
		if (trunc.length > len) {
			trunc = trunc.substring(0, len);
			trunc = trunc.replace(/\w+$/, '');
			trunc += '<a href="#" ' + 'onclick="this.parentNode.innerHTML=' + 'unescape(\''+escape(p.innerHTML)+'\');return false;">' + ' more...<\/a>';
			p.innerHTML = trunc;
		}
	}
}

function injectFluxWidget(widgetName, options)
{
	if (typeof(Flux) != "undefined" && Flux.Utils.WidgetsLoader) {
		Flux.Utils.WidgetsLoader.createWidget(widgetName, options);
	}
}

function CCEventBroadcaster(){
	this._l = [];
};
CCEventBroadcaster.prototype = {
	_l: null,
	_p: null,
	add_listener: function( obj, method ){
		if( this._index_of(obj,method)<0 )
		{
			var new_entry = new CCEventBroadcasterEntry(obj, method);
			this._l.push( new_entry );
			if( this._p != null )
			{
				new_entry.broadcast( this._p );
			}
			return true;
		}
		return false;
	},
	rem_listener: function( obj, method ){
		var i = this._index_of( obj, method );
		if( i > -1 )
		{
			this._l.splice( i, 1 );
			return true;
		}
		return false;
	},
	broadcast: function( params ){
		this._p = params==null ? [] : params;
		if( this._l.length == 1 )
		{
			this._l[0].broadcast( this._p );
		}
		else if( this._l.length > 0 )
		{
			for( var i in this._l )
			{
				this._l[i].broadcast( this._p );
			}
		}
	},
	_index_of: function( obj, method ){
		for( var i in this._l )
		{
			var l = this._l[i];
			if( l._obj == obj && l._method == method ) return i;
		}
		return -1;
	}
};
function CCEventBroadcasterEntry( obj, method ){
	this._obj = obj;
	this._method = method;
};
CCEventBroadcasterEntry.prototype = {
	_obj: null,
	_method: null,
	broadcast: function( params ){
		this._method.apply( this._obj, params );
	}
};
function clearSearch(theText) {
  	if (theText.value == theText.defaultValue) {
		theText.value = "";
	}
}
function blurSearch( theText ){
	if( theText.value == "" ){
		theText.value = theText.defaultValue;
	}
}
function submitSearch( form ){
	var field = $(form).find('input[type="text"]');
	var term = field.attr("value");
	var info = field[0].defaultValue;
	if( info == term ){
		alert( "Please enter a search term." );
		return false;
	}
	return true;
}

function loginsubmit(){
	document.flux_signin.ref.value=location.href;
	document.flux_signin.submit();
}

function validate_required(field,alerttxt)
{
	with (field)
	{
		if (value=="Search for Videos"||value=="")
		  {alert(alerttxt);return false;}
		else {return true}
		}
	}

	function validate_form(thisform)
	{
		with (thisform)
	{
	if (validate_required(searchterm,"Please enter a search term.")==false)
	  {searchterm.focus();return false;}
	}
}

function validateEmail(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == true) {
		return true;
	}
	return false;
}



