function get_session_id() {
  var re = /PHPSESSID=([^;]*)/;
  var result = re.exec(document.cookie);
  return result ? result[1] : '';
}

var photoUpload = {
  swfu: null,
  
  queued: function(file) {
    this.startUpload(file.id);
  },
  
  start: function(file) {
    $('#cms_photo_upload_progress .message').html("");
    $('#cms_photo_upload_progress .bar').css({width: '0'});
    $('#cms_photo_upload_progress').show();
    return true;
  },
  
  progress: function(file, bytesComplete, totalBytes) {
    pct = (totalBytes > 0) ? (bytesComplete / totalBytes) : 0;
    $('#cms_photo_upload_progress .bar').css({width: pct+'%'});
  },
  
  error: function(file, errorCode, message) {
    $('#cms_photo_upload_progress').hide();
    alert("Failed to upload file \""+file.name+"\":\n"+message);
  },
  
  success: function(file, response, responsReceived) {
    $('#cms_photo_upload_progress .bar').css({width: '100%'});
    $('#cms_photo_upload_progress .message').html("complete");
    $('#cms_photo_upload_progress').fadeOut('slow', function() { window.location.reload(); });
  },

  make_selection: function(value) {
    var win = tinyMCEPopup.getWindowArg('window');
    var cb = tinyMCEPopup.getWindowArg('callback');
    if (cb) {
      try { cb(value); } catch (e) { /* ignore */ }
    } else {
      win.document.getElementById(tinyMCEPopup.getWindowArg('input')).value = value;
    }
    tinyMCEPopup.close();
  },
  
  remove_photo: function(id) {
    if (!confirm("Permanently delete this file?")) return;
    
    $.ajax({
      url: '/cms/media_remove',
      type: 'POST',
      data: {id: id},
      error: photoUpload.remove_error,
      success: photoUpload.remove_success
    });
  },

  remove_error: function(xhr, status, ex) {
    alert("Could not remove file.  Server returned: " + xhr.responseText);
  },
  
  remove_success: function(data, status, xhr) {
    var elem = $('#media_file_'+data);
    elem.fadeOut('fast', function() {
      elem.remove();
    });
  }

}

$(document).ready(function () {
  initialize_flvs();
  
  if ( $.browser.msie && $.browser.version < 7.0 ) {
    $('#navigation>div').each(function () {
      this.onmouseenter = function () { $(this).addClass('hover') }
      this.onmouseleave = function () { $(this).removeClass('hover') }
    })
  }
  
  if ($('span#cms_photo_upload').size()) {
    photoUpload.swfu = new SWFUpload({
      upload_url: "/cms/media_upload",
      flash_url: "/swf/swfupload.swf",
      button_placeholder_id: "cms_photo_upload_button",
      button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
      button_text: "<span class=\"foo\">Upload New File</span>",
      button_width: 175,
      button_height: 32,
      button_text_top_padding: 10,
      button_text_style: ".foo { font-size: 11px; font-family: Verdana, sans-serif; color: #333333; }",
      button_cursor: SWFUpload.CURSOR.HAND,
      file_queued_handler: photoUpload.queued,
      upload_start_handler: photoUpload.start,
      upload_progress_handler: photoUpload.progress,
      upload_error_handler: photoUpload.error,
      upload_success_handler: photoUpload.success,
      post_params: {'PHPSESSID': get_session_id()}
    });
  }
})

function initialize_flvs () {
  $('.flv').each(function () {
    if ( $(this).parents('.editable').size() ) {
      return;
    }
    
    var url = $(this).text();
    
    initialize_flvs.sequence++;
    $(this).replaceWith(
      '<div class="flv_wrapper"><div id="flv_' + initialize_flvs.sequence
      + '"></div></div>');
    
    swfobject.embedSWF('/swf/FLVPlayer_Progressive.swf',
      'flv_' + initialize_flvs.sequence, 320, 240, '8.0.0',
      '/swf/expressInstall.swf',
      { skinName : "/swf/Clear_Skin_1", streamName : url,
        autoPlay : "false", autoRewind : "false" },
      { wmode : "transparent" });
  })
}
initialize_flvs.sequence = 0;

function initialize_disclosures ( links, container_selector, open_class ) {
  var fragment = (window.location.hash && window.location.hash != '') ?
    window.location.hash.substr(1) : false;
  
  links.each(function () {
    $(this).click(function () {
      $(this).parents(container_selector).toggleClass(open_class);
      return false;
    })
    
    if (fragment) {
      var parent = $(this).parents(container_selector);
      if (parent.hasClass(fragment))
        parent.addClass(open_class);
      else
        parent.removeClass(open_class);
    }
  })
}

// sIFR initialization
(function () {
  if ( window.editor_url || ! window.sIFR ) {
    // sIFR screws up editable blocks.
    return;
  }
  
  var avenir_light = { src : "/swf/avenir_light.swf" };
  var avenir_roman = { src : "/swf/avenir_roman.swf" };
  
  sIFR.fitExactly = true;
  sIFR.activate(avenir_light, avenir_roman);
  
  sIFR.replace(avenir_light, {
    selector : '#page_home_index h2',
    css : '.sIFR-root { color: #5fc0d1; }',
    transparent : true,
    tuneHeight : -6,
    offsetTop : -6
  });
  
  sIFR.replace(avenir_light, {
    selector : '#page_home_index #now_available h3',
    css : '.sIFR-root { color: #000000; }',
    transparent : true,
    tuneHeight : -6
  });
  
  sIFR.replace(avenir_light, {
    selector : '#page_home_index h3',
    css : '.sIFR-root { color: #5fc0d1; }',
    transparent : true,
    tuneHeight : -6
  });
  
  sIFR.replace(avenir_light, {
    selector : 'h2',
    css : '.sIFR-root { color: #ffffff; text-transform: uppercase; }',
    transparent : true,
    tuneHeight : -11
  });
  
  sIFR.replace(avenir_roman, {
    selector : '.section h3 span',
    css : '.sIFR-root { color: #939598; background-color: #ffffff; text-transform: uppercase; }',
    transparent : true,
    forceSingleLine : true,
    tuneHeight : -6
  });
  
  sIFR.replace(avenir_light, {
    selector : '.section_head h3',
    css : '.sIFR-root { color: #ffffff; text-transform: uppercase; }',
    transparent : true,
    tuneHeight : -6
  });
  
  sIFR.replace(avenir_light, {
    selector : '.section_head .toc li',
    css : 'a { color: #ffffff; font-size: 20px; text-decoration: none } a:hover { color: #ffffff; }',
    transparent : true,
    tuneHeight: -6,
    tuneWidth: 21,
    offsetLeft : 21
  });
})()

/* Editable blocks */
var block_content = null;
var block_page = null;
var block_code = null;

function editable_edit ( node, page, code ) {
  block_content = $(node).parents(".editable").find('.editable_content').get(0)
    .innerHTML;
  block_page = page;
  block_code = code;
  
  window.open(editor_url, "editor_" + page + "_" + code,
      "height=400,width=500,menubar=no,toolbar=no,location=no,resizable=yes")
    .focus();
}

function editable_set ( page_code, content ) {
  var block = $("#block_" + page_code).get(0);
  
  if ( block ) {
    block.innerHTML = content;
  }
}

function editable_popup ( url, name ) {
  window.open(url, name || "_blank",
      "height=600,width=600,menubar=no,toolbar=no,location=no,resizable=yes,"
      + "scrollbars=yes")
    .focus();
}
