/*
 * utils.js
 * 
 * Copyright 2006 (c) Digital Pulp
 * Authors: Brian Skahan <brian@digitalpulp.com>
 *          Manny Phan <manny@digitalpulp.com>
 *
 */


// On Load -----------------------------------------------
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

// Dropdown menu ------------------------------------------
startList = function() {
  if (document.all&&document.getElementById) {
    navRoot = document.getElementById("SiteMenu");
    for (i=0; i<navRoot.childNodes.length; i++) {
      node = navRoot.childNodes[i];
      if (node.nodeName=="LI") {
        node.onmouseover=function() {
          this.className+=" over";
        }
        node.onmouseout=function() {
          this.className=this.className.replace(" over", "");
        }
      }
    }
  }
}
addLoadEvent(startList);

// Printable view popup -----------------------------------
var print_win = null;
function popPrint(url) {
        print_win = window.open(url, 'printWin', 'width=800,height=600,toolbar=yes,scrollbars=yes,scrolling=yes,statusbar=no,resizable=yes');
        if (window.focus) print_win.focus();
}

// Popup handler ------------------------------------------
var client_win = null;
function popClient(url) {
        client_win = window.open(url, 'clientWin', 'width=370,height=600,toolbar=no,scrollbars=no,scrolling=no,statusbar=no,resizable=no');
        if (window.focus) client_win.focus();
}
// View Larger handler ------------------------------------------
var view_win = null;
function popView(url) {
        view_win = window.open(url, 'viewWin', 'width=390,height=600,toolbar=no,scrollbars=yes,scrolling=yes,statusbar=no,resizable=no');
        if (window.focus) view_win.focus();
}
// View Larger handler [[e-cards]]------------------------------------------
var view_win = null;
function popViewEcard(url) {
        view_win = window.open(url, 'viewWin', 'width=665,height=480,toolbar=no,scrollbars=yes,scrolling=yes,statusbar=no,resizable=no');
        if (window.focus) view_win.focus();
}
// Reset popup window sizes to fit page wrapper
resizePopup = function() {
  var x = window;
  var width = $('PopupPageWrapper').scrollWidth;
  var height = $('PopupPageWrapper').scrollHeight;
      var ua = window.navigator.userAgent
      var msie = ua.indexOf ( "MSIE " )


  if (msie > 0) {
	  height = height+60;
  }
  var myH, myW, d = x.document.documentElement, b = x.document.body;
  if( x.innerWidth ) { x.innerWidth = width; x.innerHeight = height; }
  else if( d && d.clientWidth ) {
    myW = d.clientWidth; myH = d.clientHeight;
    x.resizeTo( width, height);
  }
  if( x.focus ) { x.focus(); }
};

// show and hide the privacy policy div.
function togglePrivacyPolicy() {
  if ($('FullPrivacyPolicy')) Element.toggle($('FullPrivacyPolicy'));
}

// attach this to the onfocus of an INPUT or TEXTAREA, passing the 'this'
// object as the argument
function textFieldStoreAndClear(el) {
  el.originalText = (el.originalText == null) ? el.value : el.originalText;
  if (el.value == el.originalText) el.value = '';
}

// attach this to the onblur of an INPUT or TEXTAREA, passing the 'this'
// object as the argument
function textFieldRestore(el) {
  el.value = (el.value == '') ? el.originalText : el.value;
}

// Show and Hide Text Toggle
function toggleLayer(whichLayer) {
  if (document.getElementById) {
    // this is the way the standards work
    var style2 = document.getElementById(whichLayer).style;
    //style2.display = style2.display? "":"block";
  }
  else if (document.all) {
    // this is the way old msie versions work
    var style2 = document.all[whichLayer].style;
    style2.display = style2.display? "":"block";
  }
  else if (document.layers) {
    // this is the way nn4 works
    var style2 = document.layers[whichLayer].style;
    style2.display = style2.display? "":"block";
  }
}
// BEGIN: Generic Cookie handlers -------------------------

function getCookie( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) return null;
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) end = document.cookie.length;
  return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+"="+escape( value ) +
    ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function clearCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + "=" +
      ( ( path ) ? ";path=" + path : "") +
      ( ( domain ) ? ";domain=" + domain : "" ) +
      ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// END: Generic Cookie handlers ---------------------------


// BEGIN: MAW Cookie handlers -----------------------------

function setChapterCookies(chapter)
{
  setCookie("maw_chapter_id", chapter.id, false, '/');
  setCookie("maw_chapter_name", chapter.name, false, '/');
  setCookie("maw_chapter_phone", chapter.phone, false, '/');
  setCookie("maw_chapter_url", chapter.url, false, '/');
}

function getChapterCookies() {
  var cc = { id: getCookie("maw_chapter_id"),
             name: getCookie("maw_chapter_name"),
             phone: getCookie("maw_chapter_phone"),
             url: getCookie("maw_chapter_url") }
  return $H(cc);
}

function clearChapterCookies() {
  clearCookie("maw_chapter_id", '/');
  clearCookie("maw_chapter_name", '/');
  clearCookie("maw_chapter_phone", '/');
  clearCookie("maw_chapter_url", '/');
}

// END: MAW Cookie handlers -------------------------------

// -----------------------------------------
// Handle a single Chapter object result
function parseResultsById(xhr) {
  var list = eval('(' + xhr.responseText + ')');
  if (list.chapters.length == 0) {
    alert("No Chapter Found");
  }
  else if (list.chapters.length > 0){
    setChapter(list.chapters[0].chapter);
    $('HeaderWrapper').removeChild($('ChapterSelectionList'));
  }
  else {
    alert("Problem");
  }
}

// Handle multiple Chapter object results
// If we get more than one chapter popup a div with the list to choose from
// and call getChapterById.
function parseResultsByZip(xhr) {
  var list = eval('(' + xhr.responseText + ')');
  if (list.chapters.length == 0) {
    alert("No Chapter Found");
  }
  else if (list.chapters.length == 1){
    setChapter(list.chapters[0].chapter);
  }
  else if (list.chapters.length > 1){
    var x = document.createElement('div');
    x.id = 'ChapterSelectionList';
    var y = document.createElement('h3');
    y.appendChild(document.createTextNode("There is more than one chapter serving your zip code"));
    x.appendChild(y);
    for (var i=0;i<list.chapters.length;i++) {
      var y = document.createElement('a');
      y.href = "javascript:getChapterById('" + list.chapters[i].chapter.id + "')";
      y.appendChild(document.createTextNode(list.chapters[i].chapter.name));
      x.appendChild(y);
      document.getElementById('HeaderWrapper').appendChild(x);
    }
  }
}

function getChapterByZip(zip)
{
  var chapterRequestByZip = new Ajax.Request('/maw/chapter', { method: 'get',
                                                               parameters: 'zip=' + zip,
                                                               onSuccess: parseResultsByZip });
}

function getChapterById(id)
{
  var chapterRequestById = new Ajax.Request('/maw/chapter', { method: 'get',
                                                          parameters: 'id=' + id,
                                                          onSuccess: parseResultsById
                                                        });
  
}

// ---------------------------------------------------------
// Clear chapter cookies, reset ChapterLocator div to form
function changeChapter() {
  clearChapterCookies();
  clDiv = $("ChapterLocator");
  var clContent = "<form action='/maw/chapterlocate_results' id='chapter_locator' method='get'><label for='zip_code' class='hidden'>Zip Code</label> <input type='text' name='zip' id='zip_code' value='' /> <input type='image' alt='Go' name='GoButton' id='GoButton' src='/design/wish/images/btn.go.chapter-lookup.gif' />";
  clDiv.innerHTML = clContent;
  Event.observe($('chapter_locator'), 'submit', lookupChapter, false)
}

// -----------------------------------------------------------------------
// Fill ChapterLocator div with chapter info stored in cookies.
function showChapter() {
  var clDiv = $("ChapterLocator");
  if (getCookie("maw_chapter_name")) {
    var chapter = getChapterCookies();
    var clContent = "<address><strong>" + chapter['name'] + "</strong><br />" +
                    chapter['phone'] + "<br /><a href='http://" +
                    chapter['url'] + "'>" + chapter['url'] +
                    "</a><br /><a href='javascript:changeChapter();'>Change Your Chapter</a></address>";
    clDiv.innerHTML = clContent;
  }
}
addLoadEvent(showChapter);

function setChapter(chapter) {
  setChapterCookies(chapter);
  showChapter();
}

function lookupChapter(e) {
  getChapterByZip(e.target.zip.value);
  // This stops the form from following through to the results.  A more
  // dynamic, but possibly confusing, behavior.
  //Event.stop(e);
}

addLoadEvent(function () {
    if ($('chapter_locator')) {
    Event.observe($('chapter_locator'), 'submit', lookupChapter, false)}
});

// Caching restrictions in the CMS make it difficult to identify the pages
// that need a dark nav column (e.g. first items).
addLoadEvent(function () {
  var btn = $('BtnMnFirst') || false;
  if (btn && btn.className == "Active")
    $('NavigationColumnCap').style.backgroundImage = 'url(/design/wish/images/bkg.contentborder-leftedge-dark.gif)';
});

// Toggle mailing address fields on the contact us form.  We call it once to
// set the fields visible on errors.
function toggleMailingFields(e) {
    var target = $('postalcheck')
    $('CheckboxPostal').className = (target.checked)? 'Active':'';
    $('postalfields').style.display = (target.checked)? 'block':'none';    
}

addLoadEvent(function() {
  if ($('postalcheck')) {
    Event.observe($('postalcheck'),'click',toggleMailingFields,false)
    toggleMailingFields();
  }
});

// Force the MainColumn to a height that at least matches the navigation
// column.
function expandMainColumn () {

  // Exit on pages without breadcrumbs
  if ($('BreadCrumb')) {
    var bread_crumb = $('BreadCrumb');
  }
  else {
    return false;
  }

  // Exit on pages without known left columns
  if ($('NavigationColumn')) {
    var min_height = Element.getHeight($('NavigationColumn'));
  }
  else if ($('LeftNavWishes')) {
    var min_height = Element.getHeight($('LeftNavWishes'));
  }
  else {
    return false;
  }

  if (!document.all) {
    min_height = min_height + 225;
  }

  if (bread_crumb.offsetTop < min_height) {
    var x = document.createElement('div');
    x.style.height = (min_height - bread_crumb.offsetTop) + "px";
    bread_crumb.parentNode.insertBefore(x, bread_crumb);
  }
}
addLoadEvent(expandMainColumn);

// BEGIN: InspiredCreations Galleries ----------------------------------
function value_of_margin (str) {
  if (str.length < 1) return 0;
  str = str.split(/px/)[0];
  return parseInt(str);
}

function nextSlide () {
  var list = $('gallery_thumbnails');
  var thumbnails = list.getElementsByTagName('li');
  if (thumbnails.length < 7) return false;
  var max_offset = (thumbnails.length - 6 ) * 75;
  var margin = value_of_margin(list.style.marginLeft);
  if (Math.abs(margin) < max_offset) {
    list.style.marginLeft = String(margin - 75) + 'px'
  }
}

function prevSlide () {
  var list = $('gallery_thumbnails');
  var thumbnails = list.getElementsByTagName('li');
  if (thumbnails.length < 7) return false;
  var max_offset = 0
  var margin = value_of_margin(list.style.marginLeft);
  if (margin < max_offset) {
    list.style.marginLeft = String(margin + 75) + 'px'
  }
}

function loadGallery(el) {
  var gallery = $('Gallery');
  var caption = $('GalleryCaption');
  var thumbnails = el.parentNode.parentNode.getElementsByTagName('a');
  for (i = 0; i < thumbnails.length; i++ ) {
    thumbnails[i].className = "";
  }
  tmb = el.getElementsByTagName('img')[0];
  gallery.alt = el.title;
  gallery.title = el.title;
  gallery.src = el.href;
  caption.innerHTML = el.title
  el.className = "Active";
}

// END: InspiredCreations Galleries ----------------------------------

// This function is a workaround the EzPublish cookie handling mechanism.  It
// is used on the /help/donate page to refresh the page if a user has arrived
// from a remote site and had the mawReferrerCookie ser.
function checkReferrer() {
	var hostname = "www2.wish.org";
	var referrer = document.referrer.split('/');
	var c = getCookie("mawReferrerCookie");

	if ((referrer[2] != hostname) && c) {
	  window.location.href=window.location.href;
  }
}

