// Create NBC namespace 
var NBC = (typeof NBC=="object") ? NBC : {};

//interactive Insert 
NBC.InteractiveInsert = function() {
	
	this.ini = function() {
	
		document.write("<script type=\"text/javascript\" src=\"" + this.fDomain + "/includes/" + this.swfObjectFile + "\"><\/script><script type=\"text/javascript\">var flashvars = {xmlfile:\"" + this.fDomain + "/includes/" + this.xmlFile + "\",url:\"" + this.mDomain + "\"};var params = {wmode:\"" + this.wmode + "\",allowFullScreen:\"" + this.allowFullScreen + "\",allowScripting:\"" + this.allowScripting + "\",allowScriptAccess:\"" + this.allScriptAccess + "\"};var attributes={};attributes.id=\"" + this.attributesId + "\";swfobject.embedSWF(\"" + this.mDomain + this.embedSWFFile + "\", \"audioSSContainer\", \"" + this.audioSSContainerWidth +"\", \"" + this.audioSSContainerHeight + "\", \"" + this.audioSSContainerVersion + "\", \"\", flashvars, params, attributes)<\/script>");
		return false;
		
	};
};

//nbc contact form
NBC.ContactForm = function() {
	this.ini = function() {
		$("#contact_inp_submit").click(function(){
			var cx = new NBC.ContactForm();
			if (cx.checkEmail($("#contact_inp_email").val()) == false){
				alert("Wrong email format!");
			}
			else if ($("#contact_inp_messages").val() == ""){
				alert("You have not entered any message!");
			}
			else
			{
				$("#contactform").submit();
			}
			return false;		
		});
	}
	
	
	this.checkEmail = function(st){
		var Ex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var rs;
		if(st.match(Ex)){
			rs = true;
		}else{
			rs = false;
		}
		return rs;
	}
}

//hot topics
NBC.hotTopic = function() {
	
	this.ini = function() {
		
		$(".hot_top_plus").click(function(){
			$("#hot_topics_wrp a").removeClass("hot_top_minus");
			$(this).addClass("hot_top_minus");
			var IdArr = $(this).attr('id').split('_');
			$(".hot_top_sub").slideUp("fast",function(){
				$(this).remove();
			});
			$.ajax({
				type: "GET",
				url: "/i/dispatcher/?command=GetArticlesByTopic&topic=" + $(this).attr("title"),
				success: function(data){
						$("#Hot_top_list_" + IdArr[1]).append("<ul class='hot_top_sub' style='display:none'>" + data + "</ul>");
						$(".hot_top_sub").slideDown("fast");
					}
			});
		return false;
		});
		
	};
};

NBC.Weather = function(){
	
	//initiatest poll function
	this.ini = function()
	{
	
		$(".weather_search_box").click(function(){
			$(this).val("");		
			return false;
		});
		
		$(".weather_search_btn").click(function(){
			var w = new NBC.Weather();
			w.ToolTip();
		return false;
		});
		
		 //js widget updater
		 $(".fivedayforecast").click(function(){
			var IdArr = $(this).attr('id').split('_'); //gets ID
			var dayIdx = IdArr[2] - 1;
			$(".fivedayforecast").removeClass("weather_today");
			$(this).addClass("weather_today");
			var obj = swfobject.getObjectById("graphWidget");
			if (dayIdx > 4)
			{
				obj.updateTimeframe(gvDates.dates[5],dayIdx,gvDates.dates[dayIdx]);
			}
			else
			{
				obj.updateTimeframe(gvDates.dates[0],dayIdx,gvDates.dates[dayIdx]);
			}
			return false;
		 });

		$(".next_five_days").toggle(function(){
			$(this).text("Previous 5 days");
			$("#weather_first_5").hide();
			$("#weather_next_5").fadeIn();
			$(".fivedayforecast").removeClass("weather_today");
			$("#w_day_6").addClass("weather_today");
			var obj = swfobject.getObjectById("graphWidget");
			obj.updateTimeframe(gvDates.dates[5],2,gvDates.dates[10]);
			return false;
		},function(){
			$(this).text("Next 5 days");
			$("#weather_next_5").hide();
			$("#weather_first_5").fadeIn();
			$(".fivedayforecast").removeClass("weather_today");
			$("#w_day_1").addClass("weather_today");
			var obj = swfobject.getObjectById("graphWidget");
			obj.updateTimeframe(gvDates.dates[0],0,gvDates.dates[0]);
			return false;
		});
		$("#weather_more_wrp a").click(function(){
			$("#weather_more_wrp div").fadeIn();						
			return false;
		});
		
		$(".far").click(function(){
			$("#nbc_weather_current_title a").removeClass("current");
			$(this).addClass("current");				 
			$(".currentTemperature").html(WeatherConditions.TempInFar.TempCurrent + "&deg;F");	
			$(".currentFeel span").html(WeatherConditions.TempInFar.TempCurrentFeel + "&deg;F");
	
			for (i = 0; i < WeatherConditions.TempInFar.ForecastHigh.days.length; i++)
			{
				var divId = i + 1;
				$("#w_day_" + divId + " .hight_low").html("High " + WeatherConditions.TempInFar.ForecastHigh.days[i] + " Low " + WeatherConditions.TempInFar.ForecastLow.days[i]);
			}
			
			//updates flash widget
			var obj = swfobject.getObjectById("graphWidget");
			obj.switchToFahrenheit();

			return false;
		});
		
		$(".cel").click(function(){
			$("#nbc_weather_current_title a").removeClass("current");
			$(this).addClass("current");
			$(".currentTemperature").html(WeatherConditions.TempInCel.TempCurrent + "&deg;C");
			$(".currentFeel span").html(WeatherConditions.TempInCel.TempCurrentFeel + "&deg;C");	
			
			for (i = 0; i < WeatherConditions.TempInCel.ForecastHigh.days.length; i++)
			{
				var divId = i + 1;
				$("#w_day_" + divId + " .hight_low").html("High " + WeatherConditions.TempInCel.ForecastHigh.days[i] + " Low " + WeatherConditions.TempInCel.ForecastLow.days[i]);
			}
			
			//updates flash widget
			var obj = swfobject.getObjectById("graphWidget");
			obj.switchToCelsius();
			
		return false;
		});
		
		return false;
	}
	
	this.ToolTip = function()
	{
		var sVal = $(".weather_search_box").val();
		var sValArr = sVal.split(', ');
		var UrlArr = window.location.href.split('/'); //gets domain
		var url = "http://" + UrlArr[2] + "/i/location_lookup/?loc=" + $(".weather_search_box").val();
		var PostUrl;
		if (UrlArr[4] == "maps")
		{
			PostUrl = "http://" + UrlArr[2] + "/weather/maps/?zipCode="
		}
		else
		{
			PostUrl = "http://" + UrlArr[2] + "/weather/?zipCode="
		}
		
		
		$.ajax({
			type: "GET",
			url: url,
			dataType: "json",
				success: function(json){
			
			//if there is just one result
			if (json.locations.count == 0)
			{
				$(".search_wrp").remove(".search_overlay").append("<div class='search_overlay'><p>No Match Found.<br /> Please check your zip code.</p></div>");
			}
			else
			{
				//redirets if only one result
				if (json.locations.count == 1)
				{
					window.location = PostUrl + json.locations.location.zip;
				}
				else
				{
					//tryes to match city state sting
					if (sValArr.length > 1)
					{ 
						var locIndex;
						var locMateched = false;
												
						for (i = 0; i < json.locations.location.length; i++)
						{
							if (json.locations.location[i].state.toLowerCase() == sValArr[1].toLowerCase() && json.locations.location[i].city.toLowerCase() == sValArr[0].toLowerCase())
							{
								locIndex = i;
								locMateched = true;
							}
						}
						
						//decides match action
						if (locMateched == true)
						{
							window.location = PostUrl + json.locations.location[locIndex].zip;
						}
						else
						{
							var w = new NBC.Weather();
							w.GenToolTip(json.locations.location, PostUrl);
						}
					}
					//offer suggested cities
					else
					{
						var w = new NBC.Weather();
						w.GenToolTip(json.locations.location, PostUrl);
					}
				}
			}
			
			}
		});
	
	}//end of toolTip
	
	
	//initiatest poll function
	this.GenToolTip = function(locObj, PostUrl)
	{
		var citiesHTML = "";
		for (i = 0; i < locObj.length; i++)
	{
		citiesHTML = citiesHTML + "<a class='s_overlay_link' href='" + PostUrl + locObj[i].zip  + "'>" + locObj[i].city + ", " + locObj[i].state + "</a>";
	}
		$(".search_wrp").remove(".search_overlay").append("<div class='search_overlay'><p>" + citiesHTML + "</p></div>");
	}
	
	
} // end of NBC Weather


//galerry class
NBC.Gallery = function(){
	
	//initiatest gallery
	this.ini = function()
	{
		var scrollIncrement = 6;
		scrollIncrement = scrollIncrement + 1;
		var gallerySize = $('.gallery_thumb').size() - 1;
		var scrollToId = scrollIncrement;
		var galleryCurrentIdex = 1;
		
		$('.gallery_thumb').click(function(event) { //swaps main image with selected full size gallery thumbnail
			
			//get id
			var IdArr = $(this).attr('id').split('_');
			var strThmbId = "";
			strThmbId = IdArr[2];
			var imgIndex = strThmbId; //not sure if this is to be removed
			galleryCurrentIdex = parseInt(strThmbId);
	
			$(".gallery_thumb").removeClass("selected");
			$(this).addClass("selected");
			
			//creates update object
			var x = new NBC.Gallery();
			x.UpdImg(strThmbId);
			return false;
		})
		
		// next/previous 
		$('#info_box a.next').click(function(event) { //load next image in gallery
			$(this).css('visibility','visible');
			
			if (galleryCurrentIdex == $('.gallery_thumb').size())
			{
				galleryCurrentIdex = 1;
			}
			else
			{
				galleryCurrentIdex = galleryCurrentIdex + 1;
			}
				
			var x = new NBC.Gallery();
			x.UpdImg(galleryCurrentIdex);
			var prevIndex = galleryCurrentIdex + 1;
			$(".gallery_thumb").removeClass("selected");
			$("#Gallery_Thumb_" + galleryCurrentIdex).addClass("selected");
			
			return false;
		})
		
		// next/previous 
		$('.gallery_thumb_more').click(function(event) { //more
			if($(this).text() == "more")
			{
				$('.thumb_caption').html(gallery_thmbs[galleryCurrentIdex].caption);
				$(this).text("less");
			}
			else
			{
				$('.thumb_caption').html(gallery_thmbs[galleryCurrentIdex].caption_summary);
				$(this).text("more");
			}
			return false;
		})
		
		
		
		$('#info_box a.prev').click(function(event) { //load previous image in gallery
			
			if (galleryCurrentIdex == 1)
			{
				//$(this).css('visibility','hidden');
			}
			else
			{
				galleryCurrentIdex = galleryCurrentIdex - 1; 
				$(this).css('visibility','visible');
				var x = new NBC.Gallery();
				x.UpdImg(galleryCurrentIdex);
				var prevIndex = galleryCurrentIdex - 1;
				$(".gallery_thumb").removeClass("selected");
				$("#Gallery_Thumb_" + galleryCurrentIdex).addClass("selected");
			}
			return false;
		})
		
		//scrolling next
		$('#thumbnail_container a.next').click(function(event) { //scrolls thumbnail strip forward
			var _gallerySize;
			_gallerySize = gallerySize + 1;
			if (_gallerySize >= scrollIncrement)
			{
				var $mask = $('li.mask');
				var lastPos = gallerySize - 4;
				if (scrollToId >= lastPos)
				{
					scrollToId = lastPos;
				}
				$mask.stop().scrollTo($('#Gallery_Thumb_' + scrollToId), 800, {axis:'x'});
				scrollToId = scrollToId + 6;
				return false;
			}
	
		return false;
		})
		
		//scrolling previous
		$('#thumbnail_container a.prev').click(function(event) { //scrolls thumbnail strip back		
			var $mask = $('li.mask');
			scrollToId = 1;
			$mask.stop().scrollTo($('#Gallery_Thumb_' + scrollToId), 800, {axis:'x'});
			scrollToId = scrollIncrement;
			return false;
		})	
	
	}
	
	//update image class class
	this.UpdImg = function(strThmbId)
	{
		$('#image_number').html("Image " + strThmbId + " of " + $('.gallery_thumb').size());
		$('div.gallery_image > div').css('background-image','url('+gallery_thmbs[strThmbId].fullImage+')');
		$('.author').html(" " + gallery_thmbs[strThmbId].credit);
		$('.gallery_thumb_more').text("more");

		if (gallery_thmbs[strThmbId].caption_summary == undefined)
		{
			$('.thumb_caption').html(gallery_thmbs[strThmbId].caption);
			$('.gallery_thumb_more').hide();
		}
		else
		{
			$('.thumb_caption').html(gallery_thmbs[strThmbId].caption_summary + "");
			$('.gallery_thumb_more').show();
		}
		
		if(gallery_thmbs[strThmbId].credit == "")
		{
			$('.byauthor').hide();
		}
		else
		{
			$('.byauthor').hide();
		}
		
		return false;
	}
	
}


NBC.Poll = function(){	
	//initiatest poll function
	this.ini = function()
	{
		$('.poll_list a').click(function(event) {
			event.preventDefault();
	
			var pollCookieName = "nbcp" + poll_setting.pid;
			var pollCookieValue = null;
			var results = document.cookie.match ('(^|;) ?' + pollCookieName + '=([^;]*)(;|$)');
			if(results) {
			   pollCookieValue = unescape(results[2]) ;
	 		}
		
			if(pollCookieValue != null) {
				// that means user already voted, just show the results
				$('.poll_list').hide();
				$('.pollResults').fadeIn("fast");
				$('.poll_result_link').text("");
			}
			else {			
				// otherwise user hasnt voted yet. set the cookie and submit vote to server
				document.cookie = pollCookieName + "=y";
				var IdArr = $(this).attr('id').split('_'); //gets ID
				var UrlArr = window.location.href.split('/'); //gets domain				 
				var url = 'http://' + UrlArr[2] + '/i/pollsubmit/?pid=' + poll_setting.pid + '&mr=1&cid=' + poll_setting.cid + '&oid=' + IdArr[2] + '&submit=Submit';
				$.ajax({
					type: "GET",
					url: url,
					dataType: "json",
					success: function(json){
						if (json.poll_response.sucess_code == 1) {						
							var i;
							for(i in json.poll_response.results) {
							    var id = parseInt(i) + 1;
							    var pollAnswerId = "poll_answer_" + id;
							    var pollAnswerBarId = "poll_answer_bar_" + id;
								var percent = json.poll_response.results[i];
								document.getElementById(pollAnswerId).innerHTML = percent;
								document.getElementById(pollAnswerBarId).style.width = percent;
							}
							$('.poll_list').hide();
							$('.pollResults').fadeIn("fast");
							$('.poll_result_link').text("");								
						}				
					}
				});
				
			}
			return false;
		});
		
		
		$('.poll_more_questions').click(function() {
												 
			if ($(this).text() == "see results")								 
			{
				$('.pollResults').fadeIn();
				$(this).text("back to poll");
				$('.poll_list').hide();
			}
			else
			{
				$('.pollResults').hide();
				$(this).text("see results");
				$('.poll_list').fadeIn();
			}
			
	
			return false;
		});
		
		return false;
	}
	
} // end of NBC poll


//nbc flag
NBC.flagComment = function() {
	this.ini = function() {
		$('li.comment a.redlinksm').click(function(event) {
			event.preventDefault();
			$(event.target).replaceWith('<p class="commentflagged">This comment has been flagged for moderation.</p>');
			$.get(
				document.URL,
				{f:'y',orderpar:'regular',com:'1'}
			);
		});
	}
}


//bookmark this article page

NBC.bookmarks = function() {
	this.bookmark = function(url,title) {
		if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
 		window.external.AddFavorite(url,title);
	  } else if (navigator.appName == "Netscape") {
	    window.sidebar.addPanel(title,url,"");
	  } else {
	    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
	  }
	}	
}


//here is your namespaced new class
NBC.newFunctionGoesHere = function(){
	//this is an empty namespace if you want to add new stuff
}

//end of namespace for now



function popUp(URL) { 
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=400,height=600,left = 640,top = 225');");
}

function enterKeyPressed(e) { //e is event object passed from function invocation
    var characterCode; // literal character code will be stored in this variable

    if (e && e.which){ //if which property of event object is supported (NN4)
        e = e;
        characterCode = e.which; //character code is contained in NN4's which property
    }
    else {
        e = event;
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }

    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        return true;
    }   
    else{
        return false;
    }
}


<!-- Begin Hightlight and Copy text in text field

function copyit(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
therange=tempval.createTextRange()
therange.execCommand("Copy")
}
//  End -->


var gallery_thmbs=new Array();

$(document).ready(function(){
	//start fuctions(onload)/

	//initiatest poll ajax
	var pl = new NBC.Poll();
	pl.ini();
	
	//weather ini
	var wthr = new NBC.Weather();
	wthr.ini();
	
	//hot topics
	var hot = new NBC.hotTopic();
	hot.ini();
	
	//calls ajax page DELETE
	$("#mynav a").click(function(){
		$(this).addClass("selected");
	return false;
	});


	//search taggle function
	$("#more_taggle").click(function(){
		if($(this).attr("class") != "open")
		{
			$("#more_options").show();
			$(this).text("» Less Options");
			$(this).addClass("open")
		}
		else
		{
			$("#more_options").hide();
			$(this).text("» More Options");
			$(this).removeClass("open")
		}
	return false;
	});
	
	// call for captions up and down
	
	 $(".box").click(function(){
		var IdArr = $(this).attr('id').split('_'); //gets ID
		$("#imgCaption_" + IdArr[1]).fadeIn("fast");
	return false;
	});
	
	$(".overlayBox").click(function(){
	$(this).fadeOut("slow");
	return false;
	});
	
	$(".jqmClose").click(function(){
		var IdArr = $(this).attr('id').split('_'); //gets ID
		$("#jqm_cont_" + IdArr[2]).empty();
	});


//end onload//
});

/* 

	Blankwin function 
	written by Alen Grakalic, provided by Css Globe (cssglobe.com)
	please visit http://cssglobe.com/post/1281/open-external-links-in-new-window-automatically/ for more info
	
*/

this.blankwin = function(){
	var hostname = window.location.hostname;
	var startIndex = hostname.indexOf("www.") + 4;
	
	hostname = hostname.substring(startIndex).toLowerCase();
	var a = document.getElementsByTagName("a");	
	this.check = function(obj){
		var href = obj.href.toLowerCase();
		return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;				
	};
	this.set = function(obj){
		obj.target = "_blank";
		//obj.className = "external";
	};	
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};
};



// script initiates on page load. 

this.addEvent = function(obj,type,fn){
	if(obj.attachEvent){
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn](window.event );}
		obj.attachEvent('on'+type, obj[type+fn]);
	} else {
		obj.addEventListener(type,fn,false);
	};
};
addEvent(window,"load",blankwin);

