function showSigninForm(){
	if ( (document.getElementById("signinFormHolder")) && (document.getElementById("signinFormHolder").style.display=="block") ){
		alert("Please use the sign-in form to sign-in to your comedycentral.com account.");
		if (document.signinForm) document.signinForm.userName.focus();
	} else {
		if (document.getElementById("signinFormHolder")) document.getElementById("signinFormHolder").style.display="block";
		if (document.getElementById("blog_CenterContentHolder")) document.getElementById("blog_CenterContentHolder").style.display="none";
		if (document.signinForm) document.signinForm.userName.focus();
	}//end else
}//end showSigninForm()

function userSigninSuccess(){
	document.location=document.location;
}//end userSigninSuccess()

function closeSigninForm(){
	if (document.getElementById("signinFormHolder")) document.getElementById("signinFormHolder").style.display="none";
}//end closeSigninForm()


function clearText(thefield){
	if (thefield.defaultValue==thefield.value) {
		thefield.value = ""
	}
	return false;
} 

//Override launchMedia To Redirect Video Launch Calls
function launchMedia(mpVars){
	var queryStringParams="?";
	var parentWinUrl = mpVars.url;
	var currentFullURL = document.location;
	var parentWinReturn="";
	
	var itemId = "";
	if ((mpVars.itemId!=undefined)&&(mpVars.itemId!="none")&&(mpVars.itemId!=""))itemId = mpVars.itemId;
	
	var popWin=null;
	var popWinUrl;
	var popWinWidth;
	var popWinHeight;
	var popWinScrollbars;
	var popWinResizable;
	var popWinLocation;
	var popWinToolbar;
	var popWinBlocked=false;
	var popWinStatus;
	var localHost="";	
	//if(!window.hasCCHeader)localHost="http://www.comedycentral.com";
	if(mpVars){
		if(mpVars.linkType=="photoGallery"){
/*************************************************** PHOTO GALLERY ***************************************************/
			messageType="photo gallery";
			var imgId="";
			if ((mpVars.imgId!=undefined)&&(mpVars.imgId!="none")&&(mpVars.imgId!=""))imgId = mpVars.imgId;			popWinUrl=localHost+"/sitewide/photo_gallery/photo_gallery.jhtml?skin=skins/SBS_photo-slideshow2.swf&style=styles/sbs_style.css&adstyle=styles/sbs_style.css&pgid="+itemId+"&imgId="+imgId;
			popWinName="cc_photo_gallery";
			popWinWidth=750;
			popWinHeight=500;
			popWinScrollbars=0;
			popWinResizable="no";
			popWinStatus="no";
			popWinLocation=0;
			popWinToolbar=0;
		} else if(mpVars.linkType=="game"){
/*************************************************** GAME ***************************************************/
			messageType="game";
			popWinUrl=localHost+"/sitewide/game_player/gameplayer_popup.jhtml?game="+itemId;
			popWinName="cc_game_player";
			popWinWidth = mpVars.width;
			popWinHeight = mpVars.height;
			if ((popWinWidth==undefined)||(popWinWidth=="")||(popWinWidth==null)) popWinWidth = 690;
			if ((popWinHeight==undefined)||(popWinHeight=="")||(popWinHeight==null)) popWinHeight = 495;
			popWinScrollbars=0;
			popWinResizable="no";
			popWinStatus="no";
			popWinLocation=0;
			popWinToolbar=0;
		} else{			
/*************************************************** MOTHERLOAD VIDEO ***************************************************/
			messageType="motherload video";				
			popWinName="cc_motherload_player";
			if ((mpVars.ml_video!=undefined)&&(mpVars.ml_video!="none")&&(mpVars.ml_video!=""))itemId = mpVars.ml_video;				
		}
		if(popWinName=="cc_motherload_player"){
			document.location="/blog.jhtml?c=vc&videoId=" + itemId;
		} else {
			if((parentWinUrl=="undefined")||(parentWinUrl==null)||(parentWinUrl=="")){
				parentWinUrl="#";
				parentWinReturn="return false;";			
			}	popWin=window.open(popWinUrl,popWinName,"width="+popWinWidth+",height="+popWinHeight+",scrollbars="+popWinScrollbars+",resizable="+popWinResizable+",location="+popWinLocation+",toolbar="+popWinToolbar+",status="+popWinStatus);		
			if(popWin!=null&&typeof (popWin)!="undefined"){
				if((parentWinUrl!="undefined")&&(parentWinUrl!=null)&&(parentWinUrl!="#")&&(parentWinUrl!="none"))document.location=parentWinUrl;
				popWin.focus();
			}else{							
				var errorAlertText="You may have a pop-up blocker interfering with your ability to view this "+messageType+".\nPlease consult the red box on this page for further instructions on how to launch the "+messageType+" you requested.";
				var errorDivText="Uh-oh -- you may have a pop-up blocker interfering with your ability to view this "+messageType+". To see the " + messageType + ", <strong>click here</strong></a><br /><br />";
				var errorDivHref="<div class=\"text\" style=\"text-align:center;\"><a href=\""+parentWinUrl+"\" onClick=\"window.open(\'"+popWinUrl+"\',\'"+popWinName+"\',\'width="+popWinWidth+",height="+popWinHeight+",scrollbars="+popWinScrollbars+",resizable="+popWinResizable+",location="+popWinLocation+",toolbar="+popWinToolbar+",status="+popWinStatus+"\');"+parentWinReturn+"\">" + errorDivText + "</a></span>";			
			
				if (document.getElementById("popUpError")) popErrorEvent(errorAlertText,errorDivHref);
				else addLoadEvent(popErrorEvent(errorAlertText,errorDivHref));									
			}			
		}
	}else alert("Improperly Formatted Launch Media Call\nPlease pass an appropriate object.");
}

function addLoadEvent(func){
	try{ 
    	if(window.attachEvent){window.attachEvent("onload",func);} 
        if(window.addEventListener){window.addEventListener("load",func,false);} 
        return this; 
    }catch(e){} 
}

function openNewsletter(theURL,winName,features) { 
  // Mac users need a menubar 
  if (navigator.appVersion.indexOf("Mac") > 0) {features+=",menubar"}
  window.open(theURL,winName,features); 
}


function submitNewsletter(email) {
	if(email != '' && email != 'Enter Your Email Address' && isValidEmail(email)){
		var pars = 'newsletter=1172823250&email='+email;
		document.getElementById("newsletterbox").innerHTML =  "Please Wait...";
		ccHttpRequest('/colbertreport/mini_site_files/includes/newsletter_submit.jhtml', pars, "showResponse()"); 																		
		var text_field = false;
	}else{
		alert('Please enter a valid email address.');
		return false;
	}
}

function showResponse () {
	document.getElementById("newsletterbox").innerHTML =  cc_http_request.responseText ? cc_http_request.responseText : cc_http_request.responseXML;
}

function clearDefault(el) {
  if (el.defaultValue==el.value) el.value = ""
}

/*
 * performs numerous checks on email address to ensure it is valid
 */
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

/*
 * checks that all characters in a string are vaild for an email address
 */
function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}



/*
 * Sets up highlight state for the left nav
 */
function activateLeftNav() {
	var epId = getUrlParameter('episodeId');
	var vId = getUrlParameter('videoId');
	var cId = getUrlParameter('collectionId');
	var pageName = window.location.pathname;
	if(epId=='' && vId==''&& cId=='' ){
		// no episode, video or collection.  
		// check pages
		if(pageName== '/colbertreport/tickets.jhtml'){
			$('#menu-tickets').addClass('active');
		}
		if(pageName == '/colbertreport/about.jhtml'){
			$('#menu-about').addClass('active');
		}
		if(pageName == '/colbertreport/index.jhtml' || pageName == '/colbertreport/'){
			$('#menu-home').addClass('active');
		}
		return;
	} else {
		if(epId!='' && document.getElementById(epId)) {
			el = document.getElementById(epId);
			if (el.className == 'episodeNavItem last') {
				el.className = 'episodeNavItem_active last';
			} else {
				el.className = 'episodeNavItem_active';
			}
			return;
		}
		if(vId!='' && document.getElementById(vId)) {
			el = document.getElementById(vId);
			if (el.className == 'videoNavItem last') {
				el.className = 'videoNavItem_active last';
			} else {
				el.className = 'videoNavItem_active';
			}
			return;
		}
		if(cId!='' && document.getElementById(cId)) {
			el = document.getElementById(cId);
			if (el.className == 'videoNavItem last') {
				el.className = 'videoNavItem_active last';
			} else {
				el.className = 'videoNavItem_active';
			}
			return;
		}
		return;
	}
}

/*
 * This method extracts any parameter from an URL
 */
function getUrlParameter(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ) {
    return "";
  } else {
    return results[1];
   }
}

/*
 * This method injects some extra styling into
 * the ticketing system.
 */
function styleTickets() {
	try {
		// there are two frames - we need to target both of them
		ticketingFrame = window.frames['ticketing-frame'];
		calendarFrame = window.frames['ticketing-frame'].frames[0];
		if(calendarFrame) {
			loadjscssfile('/colbertreport/mini_site_files/includes/tickets.css', 'css',calendarFrame);
			$(calendarFrame).unload(function(){
				window.setTimeout(top.styleTickets, 100);
				top.styleTickets();
				$(this).load(function(){
					alert('loaded');
					top.styleTickets();
				});
			});
		} 
		if(ticketingFrame) {
			loadjscssfile('/colbertreport/mini_site_files/includes/tickets.css', 'css',ticketingFrame);
		} 
	} catch(e) { }

}

/*
 * This method injects either css or js into any target
 * if no target specified it loads into current window
 */
function loadjscssfile(filename, filetype, target){
	if(target=='') {
		domTarget = document;
	} else {
		domTarget = target.document;
	}
	if (filetype=="js"){ //if filename is a external JavaScript file
		var fileref=domTarget.createElement('script')
		fileref.setAttribute("type","text/javascript")
		fileref.setAttribute("src", filename)
	}
	else if (filetype=="css"){ //if filename is an external CSS file
		var fileref=domTarget.createElement("link")
		fileref.setAttribute("rel", "stylesheet")
		fileref.setAttribute("type", "text/css")
		fileref.setAttribute("href", filename)
	}
	if (typeof fileref!="undefined") {
		domTarget.getElementsByTagName("head")[0].appendChild(fileref);
	}
}

/*
 * ie doesn't play nice.
 * we gotta do some fixes here, to make sure the UX is consitent
 */
function fixIeImages() {
	if (!jQuery.browser.msie) {
		// if this isn't ie, get out!
		return;
	}
	// get all basic promoTouts and the videoList and apply the link to the image
	$('.promo>a, .promo.videoList a').each(function(i){
		var link = $(this).attr('href');
		$(this).find('img').click(function(){
			window.location.href = link;
		});
	});
}

/*
 * handles the popup behaviour for the share button
 */
function prepareSharePopup() {
	
	var showPopup = function(e) {
		if (this.getAttribute('rel')) {
			var popupId = this.getAttribute('rel');
			$('#'+popupId).addClass("dialog_active");
			return false;
		}
	}
	
	var hidePopup = function(e) {
		if (this.getAttribute('rel')) {
			var popupId = this.getAttribute('rel');
			$('#'+popupId).removeClass("dialog_active");
			return false;
		}
	}
	
	// share button
	$(".sn_link").click(showPopup);
	
	//  popup 
	$(".dialog").hover(showPopup,hidePopup);
	
	// capture and cancel the click state 
	$(".sn_link_dummy").click(hidePopup);
	
	// close button 
	$(".dialog_close").click(hidePopup);
	
	// copy button 
	$(".dialog_copy").click(
		function() {
			if (this.getAttribute('rel')) {
				var copyId = this.getAttribute('rel');
				copy(document.getElementById(copyId));
				alert('the url has been copied to your clipboard');
			} 
		}
 	);
	
	// embed field auto copies to clipboard 
	$(".embed_url").click(
		function() {
			var copyId = this.getAttribute('rel');
			copy(this);
			alert('the embed code has been copied to your clipboard');
		}
 	);
}

/*
 * cross-browser copy functionality.
 * Mozilla has tighter security, so we use Flash to bypass them :)
 * 
 */
function copy(inElement) {
  if (inElement.createTextRange) {
    var range = inElement.createTextRange();
    if (range) {
      range.execCommand('Copy');
	}
  } else {
  	try {
	    var flashcopier = 'flashcopier';
	    if(!document.getElementById(flashcopier)) {
	      var divholder = document.createElement('div');
	      divholder.id = flashcopier;
	      document.body.appendChild(divholder);
	    }
	    document.getElementById(flashcopier).innerHTML = '';
	    var divinfo = '<embed src="/colbertreport/images/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	    document.getElementById(flashcopier).innerHTML = divinfo;
	} catch (e) {
		alert('There was a problem copying to your clipboard.  This may be due to FlashBlocker or similar technology');
	}
  }
}

addLoadEvent(fixIeImages);
addLoadEvent(activateLeftNav);
addLoadEvent(prepareSharePopup);
