// Create NBC namespace 
var NBC = (typeof NBC=="object") ? NBC : {};

NBC.Helpers = function() {
    // refresher
  this.attRefresher = function(att, elmId) {
    $(elmId).attr(att, $(elmId).attr(att));
    return false;
  };
    // ad iframe refresher
  this.AdFrameRefresher = function(elmId) {
    var ifSrc = $(elmId).attr("src");
    if(ifSrc!=undefined) {
      var arrS = ifSrc.split("ord=");
      $(elmId).attr("src", arrS[0] + "ord=" + Math.round(Math.random()*1000000000000) + "?");
    }
    return false;
  };
}; // end of Helpers

  // Gallery Switch for section pages and home page
NBC.Gallery_Switch = function() {
    // initiatest gallery
  this.ini = function() {
    var current = 1;
    var total = $('.entry').length;
    $('#nav_p').fadeIn('normal');
	$('#nav_n').fadeIn('normal');
	$('.entry').hide();
    $('#pic1').fadeIn('normal');
	$('#gallery_multimedia_loading').fadeOut('fast');
    $('a.previous').click(function() {
      G.doPixelTracking(8);
      var prev = current - 1;
      if (prev < 1) {
        prev = total;
      }
      $('#pic' + current).fadeOut('normal');
      $('#pic' + prev).fadeIn('normal');
      current = prev;
      return false;
    });
    $('a.next').click(function() {
      G.doPixelTracking(8);
      var next = current + 1;
      if (next > total) {
        next = 1;
      }
      $('#pic' + current).fadeOut('normal');
      $('#pic' + next).fadeIn('normal');
      current = next;
      return false;
    });
  };
}; // End of Gallery Switch

  // Gallery 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");
        // track the slideshow click event
      G.doPixelTracking(51,true);
        // create 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;
      }
        // track the slideshow click event
      G.doPixelTracking(51,true);
      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');
          // track the slideshow click event
        G.doPixelTracking(51,true);
        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) {
      // refreshers ads
    var rf = new NBC.Helpers();
    rf.AdFrameRefresher("#nbcad_300x250_iframe");
    rf.AdFrameRefresher("#nbcad_728x90_iframe");
    $('#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;
  };
};

  // interactive Insert
NBC.InteractiveInsert = function() {
  this.ini = function() {
    document.write("<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;
    });
	
	$("#weather_change_loc").submit(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(){
    	$(".currentLocation").fadeOut();	
      $("#weather_more_wrp div").fadeIn();
		return false;
    });
	
	$("#weather_currentLocation a").click(function(){
		$(".currentLocation").fadeOut();												 
		$("#weather_more_wrp div").fadeIn();
		return false;
	});	
	
	$(".weather_form_close_arrow").click(function(){
		$("#weather_more_wrp div").fadeOut();		
		$(".currentLocation").fadeIn();
		return false;
	
	
	});
    
    $(".far").click(function(){
      $("#nbc_weather_current_title a").removeClass("current");
	  $("#weather_degrees_wrp a").removeClass("current");
      $(this).addClass("current");         
      $(".currentTemperature").html(WeatherConditions.TempInFar.TempCurrent + "&deg;F");
	  $("#nbc_weather_embed_wrp .currentTemperature").html(WeatherConditions.TempInFar.TempCurrent + "&deg;F");
	  $("#embed_weather_today .temp_hight_embed").html(WeatherConditions.TempInFar.ForecastHigh.days[0] + " |");
	  $("#embed_weather_today .temp_low_embed").html(WeatherConditions.TempInFar.ForecastLow.days[0]); 
	  $("#embed_weather_tonight .temp_hight_tonight").html(WeatherConditions.TempInFar.ForecastHigh.days[0]); 
	  $("#embed_weather_tonight .temp_low_tonight").html(WeatherConditions.TempInFar.ForecastLow.days[0]); 
	  $("#embed_weather_tomorrow .temp_hight_tomorrow").html(WeatherConditions.TempInFar.ForecastHigh.days[1]); 
	  $("#embed_weather_tomorrow .temp_low_tomorrow").html(WeatherConditions.TempInFar.ForecastLow.days[1]); 
	  $(".currentFeel span").html(WeatherConditions.TempInFar.TempCurrentFeel + "&deg;F");
      $(".currentDewPoint span").html(WeatherConditions.TempInFar.TempCurrentDewPoint + "&deg;F");
      $(".todayTemperature span").html(WeatherConditions.TempInFar.ForecastHigh.days[0] + "&deg;F");
      $(".tonightTemperatureLow").html(WeatherConditions.TempInFar.ForecastLow.days[0] + "&deg;F");
      $(".tomorrowTemperature .temp_hight").html(WeatherConditions.TempInFar.ForecastHigh.days[1] + "&deg;F");
      $(".tomorrowTemperature .temp_low").html(WeatherConditions.TempInFar.ForecastLow.days[1] + "&deg;F");
      
      for (i = 0; i < WeatherConditions.TempInFar.ForecastHigh.days.length; i++)

      {
        var divId = i + 1;
        $("#w_day_" + divId + " .temp_hight").html(WeatherConditions.TempInFar.ForecastHigh.days[i]);
        $("#w_day_" + divId + " .temp_low").html(WeatherConditions.TempInFar.ForecastLow.days[i]);
      }
      
      return false;
    });
    
    $(".cel").click(function(){
      $("#nbc_weather_current_title a").removeClass("current");
	  $("#weather_degrees_wrp a").removeClass("current");
      $(this).addClass("current");
      $(".currentTemperature").html(WeatherConditions.TempInCel.TempCurrent + "&deg;C");
	  $("#nbc_weather_embed_wrp .currentTemperature").html(WeatherConditions.TempInCel.TempCurrent + "&deg;C");
	  $("#embed_weather_today .temp_hight_embed").html(WeatherConditions.TempInCel.ForecastHigh.days[0] + " |");
	  $("#embed_weather_today .temp_low_embed").html(WeatherConditions.TempInCel.ForecastLow.days[0]);
	  $("#embed_weather_tonight .temp_hight_tonight").html(WeatherConditions.TempInCel.ForecastHigh.days[0]); 
	  $("#embed_weather_tonight .temp_low_tonight").html(WeatherConditions.TempInCel.ForecastLow.days[0]); 
	  $("#embed_weather_tomorrow .temp_hight_tomorrow").html(WeatherConditions.TempInCel.ForecastHigh.days[1]); 
	  $("#embed_weather_tomorrow .temp_low_tomorrow").html(WeatherConditions.TempInCel.ForecastLow.days[1]); 
	  $(".currentFeel span").html(WeatherConditions.TempInCel.TempCurrentFeel + "&deg;C");
      $(".currentDewPoint span").html(WeatherConditions.TempInCel.TempCurrentDewPoint + "&deg;C");
      $(".todayTemperature span").html(WeatherConditions.TempInCel.ForecastHigh.days[0] + "&deg;C");
      $(".tonightTemperature span").html(WeatherConditions.TempInCel.ForecastLow.days[0] + "&deg;C");
      $(".tomorrowTemperature .temp_hight").html(WeatherConditions.TempInCel.ForecastHigh.days[1] + "&deg;C");
      $(".tomorrowTemperature .temp_low").html(WeatherConditions.TempInCel.ForecastLow.days[1] + "&deg;C");
      
      for (i = 0; i < WeatherConditions.TempInCel.ForecastHigh.days.length; i++)
      {
        var divId = i + 1;
        $("#w_day_" + divId + " .temp_hight").html(WeatherConditions.TempInCel.ForecastHigh.days[i]);
        $("#w_day_" + divId + " .temp_low").html(WeatherConditions.TempInCel.ForecastLow.days[i]);
      }
      
    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){
      
	  // reset and remove the old overlays
	  $(".search_overlay").empty;
	  
      // if there are no results
      if (typeof(json.search.loc) == 'undefined')
      {
		$(".search_wrp").remove(".search_overlay").append("<div class='search_overlay'><p>No Match Found. Please check your location.</p></div>");
		
      }
	  
	  else
      {
        if (json.search.loc instanceof Array)
        {
          //offer suggested cities
          var w = new NBC.Weather();
          w.GenToolTip(json.search.loc, PostUrl);
        }
        else // redirect if there is only one result

        {
          window.location = PostUrl + json.search.loc.id;
        }
      }
      
      }
    });
  
  }//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].id  + "'>" + locObj[i].textContent + "</a>";
          }
    $(".search_wrp").remove(".search_overlay").append("<div class='search_overlay'><p>" + citiesHTML + "</p></div>");
  }
} // end of NBC Weather


NBC.Poll = function() {
    // initiatest poll function
  this.ini = function() {
    $('.poll_list a').click(function(event) {
      event.preventDefault();
        // track the poll click event (regardless whether a vote has already been recorded)
      G.doPixelTracking(16);
      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() {
        // track the poll click event
      G.doPixelTracking(16);
      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);
