/*
  Video Box:
  ------------------------
*/
var VideoBox = {
  overlay: null,

  init: function(){
    if ((document.getElementById("video-box_c"))) return;
    this.overlay = new YAHOO.widget.Panel("video-box", 
      {
        effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration:0.45 },
        close: true,
        draggable: false,
        modal: true,
        underlay: "none",
        visible: false,
        width: "444px",
        height: "415px",
        fixedcenter: true
      }
    );
    this.overlay.render();
  },
  
  show: function(link){
    this.overlay.show();
    this.overlay.cfg.setProperty("fixedcenter", false);

    var vs_pagename = "vs_pagename=" + link.getAttribute("vs_pagename");
    var vs_sitearea = "vs_sitearea=" + link.getAttribute("vs_sitearea");
    var vs_contentgroup = "vs_contentgroup=" + link.getAttribute("vs_contentgroup");
    var vs_pagetype = "vs_pagetype=flash";
    var vs_basepage = "vs_basepage=" + link.getAttribute("vs_basepage");
    var flashTagUrl = "flashtag.txt?";
    var videoTitle = link.getAttribute("title");

    var so = new SWFObject("../Newsroom/nc3.0/flash/video.swf", "swfvideo", "400", "369", "8", "#FFFFFF");
    so.addVariable("pathToVid", link.href);
    so.addVariable("pathToThumb", "screen.jpg");
    so.addVariable("flashTagUrl", flashTagUrl);
    so.addVariable("vs_pagename", vs_pagename);
    so.addVariable("vs_sitearea", vs_sitearea);
    so.addVariable("vs_contentgroup", vs_contentgroup);
    so.addVariable("vs_pagetype", vs_pagetype);
    so.addVariable("vs_basepage", vs_basepage);
    so.addVariable("pathToXML", "../Newsroom/nc3.0/xml/video_overlay.xml");
    so.addVariable("videoTitle", videoTitle);
    so.addVariable("autoplay", "true");
    so.addParam("scale", "noscale");
    so.write("videocontent");

    var closeEl = YAHOO.util.Dom.getElementsByClassName("container-close","a","video-box");

    YAHOO.util.Event.on(closeEl, "click", function(){
      if (!(document.getElementById("swfvideo"))) return;
      var swfvideo = document.getElementById("swfvideo");
      swfvideo.parentNode.removeChild(swfvideo);
    });

  }
}
function vs_click_local(arg1, arg2, arg3, arg4) {
  vs_click(arg1, arg2, arg3, arg4);
}

/*
  Top Story/Image Swapping:
  ------------------------
*/

function storyswap(activeThumb) {
  var stories = YAHOO.util.Dom.getElementsByClassName('story', 'div', 'topstories');
  for (i=0; i<stories.length; i++) {
    if (YAHOO.util.Dom.hasClass(stories[i], 'active')) {
      YAHOO.util.Dom.removeClass(stories[i], 'active');
    }
    var thumb = YAHOO.util.Dom.getElementsByClassName('thumb', 'a', stories[i])[0];
    if (activeThumb == thumb) {
      YAHOO.util.Dom.addClass(stories[i], 'active');
    }
  }
}

function showtooltip(thumb) {
	thumb.tooltip = thumb.tooltip || YAHOO.util.Dom.getElementsByClassName('tooltip', 'p', thumb)[0];
	thumb.tooltip.style.display = 'block';
}

function hidetooltip(thumb) {
	thumb.tooltip = thumb.tooltip || YAHOO.util.Dom.getElementsByClassName('tooltip', 'p', thumb)[0];
	thumb.tooltip.style.display = 'none';
}


/*
  My Links:
  ------------------------
*/

function ml_error(error_text, is_editing) {
  // if an error message isn't already displayed, show one:
  if ((document.getElementById('mylinks-error'))) return;

  ml_error_p = document.createElement('p');
  ml_error_p.appendChild(document.createTextNode(error_text));
  ml_error_p.id = "mylinks-error";
  if (is_editing) {
    // if they're editing, display error above edit form
    edit_form.parentNode.insertBefore(ml_error_p, edit_form)
  } else {
    // if they're adding, display error above add form
    mylinksList.appendChild(ml_error_p);
  }
}

function ml_error_remove() {
    // if an error message exists on the page, remove it:
    if (!(document.getElementById('mylinks-error'))) return;

    mylinks_error = document.getElementById('mylinks-error');
    mylinks_error.parentNode.removeChild(mylinks_error);
}


function ml_add_toggle() {
  if ((mylinks_add.style.display) == "none") {
    mylinks_add.style.display = "block";
    mylinks_form.style.display = "none";
    ml_error_remove();
  }
  else {
    mylinks_add.style.display = "none";
    mylinks_form.style.display = "block";
  }

  return false;
}


function ml_onload() {
  window.mylinksList = document.getElementById("mylinks-list");
  window.mylinksList.style.display = (window.mylinksList.childNodes.length > 0)?'block':'none';
  window.mylinks_count = 0;

  // set the onsubmit for the form:
  window.mylinks_form = document.getElementById("mylinks_form");
  mylinks_form.onsubmit = function() { return ml_add(this); }
  mylinks_form.style.display = "none";

  // set onclick for "Add Link":
  window.mylinks_add = document.getElementById("mylinks_add");
  mylinks_add_link = mylinks_add.getElementsByTagName("a")[0];
  mylinks_add_link.onclick = function() { return ml_add_toggle(); }

  // grab all cookies; if it finds at least 1 cookie...
  cookieList = new cookieList();
  if (!(cookieList.length > 0)) return;

  // check all cookie names and add mylinks cookies to a temp array:
  mylinks_array_temp = new Array();
  for (i=0; i<cookieList.length; i++) {
    if (cookieList[i].name.match("mylinks_link_") != null && cookieList[i].fields != 'false') {
      mylinks_array_temp.push(cookieList[i].name.replace("mylinks_link_", ""));
    }
  }

  // sort cookies by their creation date and add to new array:
  var sortNumber = function(a, b) { return a - b; }
  mylinks_array_temp.sort(sortNumber);

  mylinks_array = new Array();
  for (i=0; i<mylinks_array_temp.length; i++) {
    mylinks_array.push(mylinks_array_temp[i]);
  }

  mylinks_array_temp.length = 0;
  mylinks_count = mylinks_array.length;

  // if there's at least 1 cookie for mylinks...
  if (!(mylinks_count > 0)) return;

  // create list and add to HTML:
  ml_list = document.createElement('ul');
  mylinksList.appendChild(ml_list);
  window.mylinksList.style.display = 'block';

  // go through cookies... if a cookie is found, grab the info and display on page:
  for (i=0; i<mylinks_array.length; i++) {
    var myLinks_cookie = new cookieObject(mylinks_array[i], null, null, "mylinks_text", "mylinks_url");
    if (!(myLinks_cookie.found)) return;

    ml_showLink(mylinks_array[i], myLinks_cookie.get("mylinks_text"), myLinks_cookie.get("mylinks_url"));
  } // end for

}


function ml_showOptions(selected_li, show) {
  if (show == true) {
    // on mouseover
    selected_li.className = "show-options";
  }
  if (show == false) {
    // on mouseout...
    selected_li.className = "";
  }
}


function ml_showLink(mylinks_name, mylinks_text, mylinks_url, mylinks_action) {
  window.mylinksList.style.display = (mylinks_count > 0)?'block':'none';

  // if it's the first link being added, create a <ul> to place all the list items in:
  if (mylinks_count === 0 && mylinks_action == "add") {
    ml_list = document.createElement('ul');
    mylinksList.appendChild(ml_list);
  }

  // create and set HTML tags for list item and links
  if (mylinks_action == "edit") {
    ml_listitem = edit_form.parentNode;
  }
  else {
    ml_listitem = document.createElement('li');
    ml_listitem.id = "mylinks_link_" + mylinks_name;
  }

  ml_listitem_link = document.createElement('a');
  ml_listitem_link.setAttribute("href", mylinks_url);
  
  // if it's a non-cisco link, have it open in a new window:
  if (mylinks_url.search(/cisco.com/gi) === -1) {
    ml_listitem_link.setAttribute("target", "_blank");
  }

  ml_listitem_options = document.createElement('span');
  ml_listitem_options.className = "options";

  ml_listitem_options_box = document.createElement('span');
  ml_listitem_options_box.className = "options-box";

  ml_listitem_link_edit = document.createElement('a');
  ml_listitem_link_edit.setAttribute("href", "#");
  ml_listitem_link_edit.onclick = function() { return ml_edit_show(this); }
  ml_listitem_link_edit.className = "edit";
  edit_img = document.createElement('img');
  edit_img.src = "../Newsroom/nc3.0/images/edit.gif";
  edit_img.width = 10;
  edit_img.height = 10;

  ml_listitem_link_delete = document.createElement('a');
  ml_listitem_link_delete.setAttribute("href", "#");
  ml_listitem_link_delete.onclick = function() { return ml_delete(this); }
  ml_listitem_link_delete.className = "delete";
  del_img = document.createElement('img');
  del_img.src = "../Newsroom/nc3.0/images/del.gif"
  del_img.width = 10;
  del_img.height = 10;

  // put it all together, insert code into HTML
  ml_listitem_link.appendChild(document.createTextNode(mylinks_text));
  ml_listitem_link_edit.appendChild(edit_img);
  ml_listitem_link_delete.appendChild(del_img);
  ml_listitem_options_box.appendChild(ml_listitem_link_edit);
  ml_listitem_options_box.appendChild(ml_listitem_link_delete);
  ml_listitem_options.appendChild(ml_listitem_options_box);
  ml_listitem_options.appendChild(ml_listitem_link);
  ml_listitem.appendChild(ml_listitem_options);

  ml_listitem_options.onmouseover = function() { ml_showOptions(this.parentNode,true); }
  ml_listitem_options.onmouseout = function() { ml_showOptions(this.parentNode,false); }

  if (mylinks_action == "edit") {
    // remove the edit form, now that it's no longer needed:
    ml_listitem.removeChild(edit_form);
    ml_listitem.className = "";
  }
  else {
    ml_list.appendChild(ml_listitem);
  }

}


function ml_validate(mylinks_text, mylinks_url, is_editing, the_form) {
  if ((mylinks_text.length) == 0) {
    ml_error_remove();
    ml_error("Please enter a title for the link.", is_editing)
//    the_form.mylinks_text.focus();
    has_errors = true;
  }
  else if ((mylinks_url.length) == 0) {
    ml_error_remove();
    ml_error("Please enter a website address for the link.", is_editing);

//    the_form.mylinks_url.focus();
    has_errors = true;
  }
  else {
    // if they forget to add "http://" in the beginning of a link, add it automatically:
    if (mylinks_url.search(/http:\/\//g) === -1) {
      window.mylinks_url = "http://" + mylinks_url;
    }
    window.mylinks_url = window.mylinks_url.replace(/ /g, "%20");
    ml_error_remove();
    has_errors = false;
  }
}


function ml_add(form) {
  ml_error_remove();

  // if there's less than 5 links already, let's add the new link:
  if (mylinks_count < 5) {

    mylinks_timestamp = new Date().getTime();
    mylinks_text = form.mylinks_text.value;
    mylinks_url = form.mylinks_url.value;
    mylinks_name = "mylinks_link_" + mylinks_timestamp;

    // validate the input
    ml_validate(mylinks_text, mylinks_url, null, form);
    if (has_errors) { return false; }

    // write the data to a cookie:
    var myLinks_cookie = new cookieObject(mylinks_name, 365, "/", "mylinks_text", "mylinks_url");
    myLinks_cookie.put("mylinks_text", mylinks_text);
    myLinks_cookie.put("mylinks_url", mylinks_url);
    myLinks_cookie.write();

    // show link, update # of links:
    ml_showLink(mylinks_timestamp, mylinks_text, mylinks_url, "add");
    window.mylinksList.style.display = 'block';

    mylinks_count++;
  
    // since it all worked out, clear the form fields and put focus back on the "link text" field:
    form.mylinks_text.value = "";
    form.mylinks_url.value = "";
    form.mylinks_text.focus();

  }
  else if (mylinks_count == 5) {
    ml_error("You can only save 5 links - please remove a link if you'd like to save another.");
  }
  return false;
}


function ml_edit_show(editlink) {

  // hide add link form, remove "5 links" error message if it's there:
  mylinks_form.style.display = "none";
  mylinks_add.style.display = "block";
  ml_error_remove();

  selected_li = editlink.parentNode.parentNode.parentNode;

  // find the specific cookie
  var myLinks_cookie = new cookieObject(selected_li.id, 365, "/", "mylinks_text", "mylinks_url");
  if (!(myLinks_cookie.found)) return;

  // create the edit form/fields/buttons:
  edit_form = document.createElement('form');
  edit_form.name = "mylinks_edit_form";
  edit_form.id = "mylinks_edit_form";
  edit_form.setAttribute("action", "#");
  edit_form.onsubmit = function() { return ml_edit(this); }

  edit_form_text_label = document.createElement('label');
  edit_form_text_label.appendChild(document.createTextNode("Title:"));
  edit_form_text = document.createElement('input');
  edit_form_text.type = "text";
  edit_form_text.name = "mylinks_text";
  edit_form_text.value = myLinks_cookie.get("mylinks_text");
  edit_form_text.className = "mylinks-field";

  edit_form_url_label = document.createElement('label');
  edit_form_url_label.appendChild(document.createTextNode("URL:"));
  edit_form_url = document.createElement('input');
  edit_form_url.type = "text";
  edit_form_url.name = "mylinks_url";
  edit_form_url.value = myLinks_cookie.get("mylinks_url");
  edit_form_url.className = "mylinks-field";

  edit_form_button = document.createElement('input');
  edit_form_button.type = "image";
  edit_form_button.src = "../Newsroom/nc3.0/images/btn_save.gif";
  edit_form_button.value = "save";

  // put everything into the HTML:
  edit_form.appendChild(edit_form_text_label);
  edit_form.appendChild(edit_form_text);
  edit_form.appendChild(edit_form_url_label);
  edit_form.appendChild(edit_form_url);
  edit_form.appendChild(edit_form_button);
  selected_li.appendChild(edit_form);

  // remove the current link/edit/delete from the page:
  selected_li_links = selected_li.getElementsByTagName('span');
  for (x=0; x<selected_li_links.length; x++) { selected_li.removeChild(selected_li_links[x]); }

  return false;
}


function ml_edit(editform) {
  edit_form = editform;

  // if the existing cookie is found...
  var myLinks_cookie = new cookieObject(edit_form.parentNode.id, null, null, "mylinks_text", "mylinks_url");
  if (!(myLinks_cookie.found)) return;

  // get input; validate:
  mylinks_text = edit_form.getElementsByTagName('input')[0].value;
  mylinks_url = edit_form.getElementsByTagName('input')[1].value;

  ml_validate(mylinks_text, mylinks_url, true, edit_form);
  if (has_errors) { return false; }

  // write new data to existing cookie:
  myLinks_cookie.expires = 365;
  myLinks_cookie.accessPath = "/";
  myLinks_cookie.put("mylinks_text", mylinks_text);
  myLinks_cookie.put("mylinks_url", mylinks_url);
  myLinks_cookie.write();

  // show the updated link on the page and show the Add Link link:
  ml_showLink(null, mylinks_text, mylinks_url, "edit");
  mylinks_add.style.display = "block";

  return false;
}


function ml_delete(deletelink) {
  // get the <li> this delete link belongs to
  selected_li = deletelink.parentNode.parentNode.parentNode;

  // find the specific cookie and remove the cookie:
  var myLinks_cookie = new cookieObject(selected_li.id);
  if (!(myLinks_cookie.found)) return;
  document.cookie = myLinks_cookie.name+"=false;"+new Date(1900,0,1).toGMTString()+myLinks_cookie.accesspath; 
  

  // remove the <li> of the delete link from the page:
  selected_li.parentNode.removeChild(selected_li);

  // if they're deleting the only link available, remove the <ul> from the page, too:
  if (mylinks_count == 1) {
  	ml_list.parentNode.removeChild(ml_list);
  	window.mylinksList.style.display = 'none';
  }

  // if they're deleting a link because they hit the 5 link limit, remove the error message:
  else if (mylinks_count == 5) { ml_error_remove(); }

  // update the number of links
  mylinks_count--;

  return false;
}

/*
  Stock Ticker:
  ------------------------
*/
function toMoney(f){
  var s=""+f;
  if (f == 0) {return "0.00"; }
  if (s.indexOf('.') == -1) {return f+".00"; }
  else {s = s.substring(0,s.indexOf('.')+3); }
  return (s == Math.floor(s)) ? s + '.00' : ((s*10 == Math.floor(s*10)) ? s + '0':s);
}

function showStockTicker() {
  if (!(stockComponent != null)) return;
  if (!(document.getElementById("stockticker"))) return;
  stocktickerDiv = document.getElementById("stockticker");
  stocktickerDiv.innerHTML = '<span><strong>Cisco Stock:</strong> $' + 
  toMoney(stockComponent.price) + ' &nbsp; | &nbsp; ' + 
  stockComponent.volume_million + ' million shares</span>';
}

/*
  Customize Quick Links:
  ------------------------
*/
function ql_onload() {
  window.qlList = document.getElementById("chooserole").getElementsByTagName("option");

  // search for quick links cookie; if it's found...
  var qLinks_cookie = new cookieObject("qlinks_role", null, null, "ql_role");
  if (!(qLinks_cookie.found)) return;

  // grab last saved role id
  ql_roleid = qLinks_cookie.get("ql_role");
  ql_option = qlList[ql_roleid];

  // call grabRole() using value of selected role; set saved option as selected
  grabRole(ql_option.value, true);
  ql_option.selected = true;
}
function grabRole(file, is_loading_page) {
  // if it's not the homepage load and they're not choosing Customize Quick Links, continue...
  if ((!is_loading_page && qlList[0].selected == true)) return;

  // swap out the links:
  /*var request = getHTTPObject();
  if (request) {
    request.onreadystatechange = function() {
      parseRoleResponse(request);
    };
    
    request.open("POST", file, true);
    request.send(null);
  }*/
  var request = YAHOO.util.Connect.asyncRequest('POST',
  	file,
  	{
  		success: function(o){
  			var linklist = document.getElementById("linklist");
  			linklist.innerHTML = o.responseText;
  		}
  	},
  null);

  // if the function isn't getting called from the homepage loading; get the array position of selected <option>
  if ((is_loading_page)) return;

  for (x=0; x<qlList.length; x++) {
    if (qlList[x].selected == true) { ql_role = x; }
  }

  // write the role id to a cookie:
  var qLinks_cookie = new cookieObject("qlinks_role", 365, "/", "ql_role");
  qLinks_cookie.put("ql_role", ql_role);
  qLinks_cookie.write();
}

/*
  On page load:
  ------------------------
*/

var homepage_onload = function() {
  ml_onload(); // mylinks
  ql_onload(); // customize quick links
  showStockTicker();
  VideoBox.init();
}
YAHOO.util.Event.onDOMReady(homepage_onload);
