// Copyright © 2006 by JammerMedia, Inc., All Rights Reserved.
//
// utils.js
//
// $Source: /tmp/cvsrepo/webapps/binder/public/javascripts/lib/utils.js,v $
// $Id: utils.js,v 1.49 2008-04-23 08:13:12 kens Exp $

// User agents
var isIE = (/MSIE/.test(navigator.userAgent)) ? true : false;
var isFirefox = (/Firefox/.test(navigator.userAgent)) ? true : false;
var isSafari = (/Safari/.test(navigator.userAgent)) ? true : false;
var isOpera = (/Opera/.test(navigator.userAgent)) ? true : false;
var isNetscape = false;

// Make an ajax call
// arguments:
// url - target
// data - query string
// ajax_response - function to handle the response
//
function ajax_request(url, data, ajax_response, post) {
    var request = null;
    try {
        var ajax = 
        request = new Ajax.Request(
            url,
            { method: ((post != null) ? 'post' : 'get'), 
              parameters: data, 
              onComplete: ajax_response, 
              onException: handleException }
        );
    }
    catch (e) {
        jmi_alert(e);
    }
    return(request);
}

function sjax_request(url, data, sjax_response, post) {
    try {
        var sjax = 
        new Ajax.Request(
            url, 
            {method: ((post != null) ? 'post' : 'get'), 
                parameters: data, 
                onException: handleException,
                asynchronous: false}
        );
    }
    catch (e) {
        jmi_alert(e);
    }
    
    if (sjax_response)
        sjax_response(sjax.transport)
    
    return(sjax.transport.responseText);
}

function handleException(req, e) {
    jmi_alert(e);
}

// Launch player
// arguments:
// id - the binder id
//
function fullScreen(id, pct, url) {
    
    var params = "resizable=yes,scrollbars=1";
    
    if (!pct || pct == '1.0')
        params += ",status=no";
    else
        params += ",location=yes,toolbar=yes,directories=yes,menubar=yes";
    
    url = url ? url : "/play/play_or_edit?id="+id
    
    var win = window.open(url, "Binder"+id, params);
    
    win.moveTo(0,0);
    
    var w = screen.availWidth;
    var h = screen.availHeight;
    
    if (pct) {
        var scale = parseFloat(pct);
        w = (scale > 0.0) ? w * scale : w;
        h = (scale > 0.0) ? h * scale : h;
    }
    
    win.resizeTo(w, h);
    
    // return win;
}
// Launch present mode
// arguments:
// id - the binder id
//
function fullPresent(id, pct, url) {
    
    var params = "fullscreen=yes,resizable=yes,scrollbars=1";
    
    if (!pct || pct == '1.0')
        params += ",status=no";
    else
        params += ",location=yes,toolbar=no,menubar=no";
    
    url = url ? url : "/play/present?id="+id
    
    var win = window.open(url, "Binder"+id, params);
    
    win.moveTo(0,0);
    
    var w = screen.availWidth;
    var h = screen.availHeight;
    
    if (pct) {
        var scale = parseFloat(pct);
        w = (scale > 0.0) ? w * scale : w;
        h = (scale > 0.0) ? h * scale : h;
    }
    
    win.resizeTo(w, h);
    
    // return win;
}

function createBinder(id, pct, url, 
    name, s1, 
    desc, s2, 
    tags, s3, 
    google, s4, 
    share, s5, 
    access, cat) {

  var myurl = url + "?new_binder_name=";
  var default_name = "new binder";

  // If there's no google search term
  if ((google == s4) || (google == "")) {
    myurl += ((name == s1) || (name == "")) ? default_name : name;
    myurl += ((desc == s2) || (desc == "")) ? "" : "&new_binder_desc=" + desc;
    myurl += ((tags == s3) || (tags == "")) ? "" : "&new_binder_tags=" + tags;
  }

  // There is a google search term
  else {
    myurl += ((name == s1) || (name =="")) ? google : name;
    myurl += "&new_binder_desc=";
    myurl += ((desc == s2) || (desc =="")) ? google : desc;
    myurl += "&new_binder_tags=";
    myurl += ((tags == s3) || (tags =="")) ? google : tags;
    myurl += "&new_binder_google=" + google;
  }

  // Check if binder is public access == 1
  if (access && (access == 1)) {
  }

  // Otherwise private -- add any shared addresses 
  // for private binders
  else if ((share != s5) && (share != "")) {
    myurl += "&new_binder_share=" + share;
  }

  // Add rest of url
  myurl += "&post_access=";
  myurl += (access) ? "1" : "0";
  myurl += "&category=" + cat;

  // Open new window with our new url
  fullScreen(id, pct, myurl);
}


// Launch slide show
// arguments:
// id - the binder id
//
function slideShow(id) {
    var win = window.open("/show?id="+id, "Binder", "status=no,resizable=yes");
    win.moveTo(0,0);
    win.resizeTo(screen.availWidth, screen.availHeight);
}

function open_edit_window(binder_id, tabindex) {
    
    // Create url used to open window
    var myurl = '/edit?id=' + binder_id;
    
    // See if we're still waiting on returned binder_id for newly
    // created binder -- we're using a binder_id=-2 as flag
    if (binder_id == -2) {
        
        // Check if binder_id is ready
        binder_id = get_working_binder_id(-2);
        
        // Still not ready
        if (binder_id == -2) {
            myurl = "/edit/waiting?id=-2";
        }
        else {
            myurl = '/edit?id=' + binder_id;
        }
    }
    
    // If we've been asked to go to a specific tab, add it to url
    if (tabindex) {
        var seltab = tabindex; // tabid.selectedIndex;
        myurl +='&tab=' + seltab + '&subtab=-1';
    }
    
    // Get screen dimensions
    var w = screen.availWidth;
    var h = screen.availHeight;
    
    // Scale new window to percentage of screen
    w = w * 0.95;
    h = h * 0.85;
    
    // document.location.href = myurl;
    // return;
    
    // Create (or update) window
    var win = window.open(myurl, 'Binder'+ binder_id, 
        'resizable=yes,status=yes,location=yes,scrollbars=yes,toolbar=yes,personalbar=yes,width='+w+',height='+h);
    
    // Pop window to top
    if (win) {
        win.focus();
    }
    
    return win;
}


function set_edit_window(tabindex) {
    
    // See if we're still waiting on returned binder_id for newly
    // created binder -- we're using a binder_id = -2 as flag
    
    // Check if binder_id is ready
    var binder_id = get_working_binder_id(-2, 1);
    
    // Still not ready
    if (binder_id == -2) {
        
        var str = "set_edit_window(";
        
        if (tabindex)
            str = str + "'" + tabindex + "')";
        else
            str = str + "'null')";
        
        // We'll try again in 1 second
        setTimeout(str, 1000);
    }
    
    else {
        
        // Create url to call
        
        var myurl = '/edit?id=' + binder_id;
        
        if (tabindex) {
            myurl +='&tab=' + tabindex + '&subtab=-1';
        }
        
        document.location.href = myurl;
        document.title = "Binder" + binder_id;
        window.name = "Binder" + binder_id;
    }
}


function launch_file_upload() {
    var win = window.open("/edit/file_upload", "File Upload", "status=no,resizable=yes");
    win.resizeTo(450, 350);    
}

function wait(id) {
    if ($(id)) {
        $(id).innerHTML = 
        "<div align='center' valign='center' style='width:100%;padding-top:25%'> \
        <img src='/images/icons/wait30trans.gif'> \
        </div>";
    }
}

function show_my_menu(but, o, bid, from, copy) {
    
    mydiv = document.getElementById(o);
    
    if (mydiv) {
        
        // Check if the menu is already displayed
        if (mydiv.style.display == "block") {
            // mydiv.style.display = "none";
        }
        
        if (o == "shelf-menu")
            show_shelf_menu(bid, from, copy);
        
        else if (o == "edit-menu")
            show_edit_menu(from);
        
        else if (o == "color-menu")
            show_color_menu(mydiv, from);
        
        else if (o = 'group-menu')
            show_group_menu(bid, from)
        
        var mb = document.getElementById(but);
        var pos = findPos(mb);
        
        var w = getWinDim();
        var s = getScrollOffset();
        var right = s[0] + w[0];
        var bottom = s[1] + w[1];
        var menuw = mydiv.clientWidth ? mydiv.clientWidth : 200;
        var menuh = mydiv.clientHeight ? mydiv.clientHeight : 120;
        
        x1 = pos[0] - 2;
        x1 = ((x1 + menuw) > right) ? right - menuw : x1;
        x1 = (x1 < s[0]) ? s[0] : x1;
        
        y1 = pos[1] + 15;
        y1 = ((y1 + menuh) > bottom) ? bottom - menuh : y1;
        y1 = (y1 < s[1]) ? s[1] : y1;
        
        mydiv.style.left = x1 + "px";
        mydiv.style.top = y1 + "px";
        mydiv.style.display = "block";
        
        // mydiv.style.left = pos[0] - 5;  
        // mydiv.style.top =  pos[1] - 4; 
        // new Effect.Appear(o, { duration:0.5 }); 
        
        //if (!e) var e = window.event;
        //e.cancelBubble = true;
        //if (e.stopPropagation) e.stopPropagation();
    }
    
    return false;
}

function show_shelf_menu(bid, from, copy) {
    
    // Update menu links and position
    $("mi-share").onclick = function(){update_about(bid, "share")};
    $("mi-details").onclick = function(){update_about(bid, "summary")};
    // $("mi-add-to-group").onclick = function(){update_about(bid, "add_to_group")};
    $("mi-embed").onclick = function(){update_about(bid, "embed")};
    $("mi-present").href = "javascript:fullPresent(" + bid + ", '0.95'); hide_my_menu(null, 'shelf-menu')";
    
    if (copy == "yes") {
        $("mi-copy").href = "/shelf/copy?id=" + bid;
        $("mi-copy").style.display = "block";
    }
    else {
        $("mi-copy").style.display = "none";
    }
    if (from == "curator") {
        // $("mi-edit").href = "/edit?id=" + bid;
        $("mi-edit").href = "javascript:fullScreen(" + bid + ", '0.95'); hide_my_menu(null, 'shelf-menu')";
        $("mi-delete").href = "javascript:delete_binder(" + bid + ")";
        $("mi-edit").style.display = "block";
        $("mi-delete").style.display = "block";
    }
    else {
        $("mi-edit").style.display = "none";
        $("mi-delete").style.display = "none";
    }
}

function show_group_menu(gid, from) {
    
    // Update menu links and position
    $("mi-details").onclick = function(){update_about_group(gid, "summary")};
    $("mi-binders").onclick = function(){update_about_group(gid, "binders")};
    $("mi-members").onclick = function(){update_about_group(gid, "members")};
    
}

function show_edit_menu(from) {
    
    // Update visible items for tab menu
    if (from == "tab") {
        $("mi-add-tab").style.display = "block";
        $("mi-add-subtab").style.display = "block";
        $("mi-del-tab").style.display = "block";
        $("mi-del-subtab").style.display = "none";
        $("mi-move-tab-l").style.display = "block";
        $("mi-move-tab-r").style.display = "block";
        $("mi-move-stab-r").style.display = "none";
        $("mi-move-stab-l").style.display = "none";
    }
    
    // And subtab menu
    else {
        $("mi-add-tab").style.display = "none";
        $("mi-add-subtab").style.display = "block";
        $("mi-del-tab").style.display = "none";
        $("mi-del-subtab").style.display = "block";
        $("mi-move-tab-l").style.display = "none";
        $("mi-move-tab-r").style.display = "none";
        $("mi-move-stab-r").style.display = "block";
        $("mi-move-stab-l").style.display = "block";
    }
}

function show_color_menu(cm, from) {
    cm.which = from;
}

function show_div(mydiv, hide) {
    if ($(mydiv))
        $(mydiv).style.display = hide ? "none" : "block";
}

function colorClick(c) {
    
    var cm = $("color-menu");
    var whichColor = cm.which;;
    
    if (whichColor == 'foreColor') {
        $("tc").style.borderColor = c;
        exec_design(whichColor, c);
    }
    else {
        
        $("bc").style.borderColor = c;
        exec_design(whichColor, c);
    }
    
    cm.style.display = "none";
    
    return false;
}

function update_about(bid, type)
{
    new Ajax.Updater('about-content', '/shelf/details/' + bid + '?type=' + type, {asynchronous:true, evalScripts:true}); 
    
    hide_my_menu(null, "shelf-menu");
    return false;
}

function add_media_to_binder(myargs, myargs1) {
    new Ajax.Updater('binder-info', '/media/add_url_to_binder?' + myargs, myargs1); 
    
    return false;
}

function update_about_group(gid, type) {
    new Ajax.Updater('about-content', '/group/details/' + gid + '?type=' + type, {asynchronous:true, evalScripts:true}); 
    
    hide_my_menu(null, "group-menu");
    return false;    
}

function hide_my_menu(e, o) {
    
    mydiv = document.getElementById(o);
    
    if (mydiv) {
        mydiv.style.display = "none";
        // new Effect.Fade(o, { duration:0.5 }); 
    }
}

function delete_binder(bid) {
    if (confirm("Are you sure you want to delete")) {
        document.location = "/shelf/delete?id=" + bid;
    }
}

function findPos(obj) {
    
    var curleft = 0;
    var curtop = 0;
    
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        } 
    }
    
    return [curleft,curtop];
}

/* ---------Drag and Drop Hooks--------------------------------------------------------- */

function startDragImpl(event) {
    $('dragdrop-pane').style.left = '0px';
    $('dragdrop-pane').style.top = '0px';
    $('dragdrop-pane').style.width = document.body.clientWidth - 10;
    $('dragdrop-pane').style.height = document.body.clientHeight - 10;
    $('dragdrop-pane').style.display = '';
    $('dragdrop-pane').style.position = 'absolute';
    bdr.getTemplate().startDrag(event);
}

function finishDragImpl(event, success) {
    setTimeout("$('dragdrop-pane').style.display = 'none'", 1000);
    bdr.getTemplate().finishDrag(event, success);
}

function dragChangeImpl(draggable) {
    //$('status').innerHTML = "Dragging: left: " + draggable.element.style.left + " top: " + draggable.element.style.top;
    bdr.getTemplate().dragChange(draggable);
}

function onDropImpl(draggable, droppable, event) {
    bdr.getTemplate().onDrop(draggable, droppable, event);
}

function onMouseDownSearch(id) {
    tsel = new Effect.Highlight(id); 
}

function onMouseUpSearch(id) {
}

function onClickTemplate(id, sync) {
    bdr.getTemplate().onClick(id, sync);
}


function getTemplateMedia(template_type) {
    
    switch (template_type) {
        
        case '0':	
        case '1':	
        case '2':	
        case '3':	
        case '4': 
        default:     return null;
        
        case 5:
        case '5':
        case 6:
        case '6':
        case 7:
        case '7':    
        case 8:
        case '8':  
        case 9:
        case '9':
        case 10:
        case '10':   
        case 11:
        case '11':   return 'media0';
    }
}

function textifyTemplate(sync) {
    
    // Convert media frame to text and insert link
    var template_type = bdr.getTemplate().type;
    var new_type = '';
    
    switch (template_type) {
        
        case 0:	
        case '0':	
        case 1:	
        case '1':	
        case 2:	
        case '2':	
        case 3:	
        case '3':	
        case 4:	
        case '4':    return;
        
        case 5:
        case '5':
        case 10:
        case '10':   new_type = 't3';
        new_frame = 'if2';
        break;
        
        case 6:
        case '6':
        case 11:
        case '11':   new_type = 't3';
        new_frame = 'if1';
        break;
        
        case 7:
        case '7':    new_type = 't2';
        new_frame = 'if1';
        break;
        
        case 8:
        case '8':    new_type = 't2';
        new_frame = 'if1';
        break;
        
        case 9:
        case '9':    new_type = 't3';
        new_frame = 'if1';
        break;
        
        default:     return;
    }
    
    onClickTemplate(new_type, sync);
    
    return new_frame;
}

function onClickMedia(id) {
    
    var content = SidebarMenu.getSearch();
    var offset = SHOW;
    if (content.results.total == content.results.idx) {
        if (content.results.total%SHOW > 0) offset = content.results.total%SHOW;
    }
    
    var match = content.results.images[content.results.idx - offset + selection_];
    
    // Instrument for undo
    var midx = 0;
    push_command("bind_media " + midx);
    savemedia.push(bdr.getTemplate().media[midx]);
    
    try {
        var media = new Media(0);
        media.unmarshall(match);
        media.idx = 0;
        media.author = match.author;
        media.notes = match.notes;
        media.description = match.description;
        media.copyright = match.copyright;
        bdr.getTemplate().media[media.idx] = media;
        media.bind();
    } catch(e) {
    $('status').innerHTML = e;
}
}


function insert_media(media)
{
    try {
        
        bdr.getTemplate().media[media.idx] = media;
        media.bind();
        
    } catch(e) {
    $('status').innerHTML = e;
}
}

function getWinDim() {
    
    var x,y;
    
    if (self.innerHeight) { 
        
        // all except Explorer
        x = self.innerWidth;
        y = self.innerHeight;
    }
    
    else if (document.documentElement &&
        document.documentElement.clientHeight) {
    
    // Explorer 6 Strict Mode
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
}

else if (document.body) {
    
    // other Explorers
    
    x = document.body.clientWidth;
    y = document.body.clientHeight;
}

return [x, y];
}

function getScrollOffset() {
    
    var x,y;
    
    if (self.pageYOffset) {
        
        // all except Explorer
        
        x = self.pageXOffset;
        y = self.pageYOffset;
    }
    
    else if (document.documentElement &&
        document.documentElement.scrollTop) {
    
    // Explorer 6 Strict
    
    x = document.documentElement.scrollLeft;
    y = document.documentElement.scrollTop;
}

else if (document.body) {
    
    // all other Explorers
    
    x = document.body.scrollLeft;
    y = document.body.scrollTop;
}

return [x, y];
}


// This is for our drop down menus - and IE6
function sfHover() {
    var sfEls = document.getElementById("nav").getElementsByTagName("LI");
    for (var i=0; i<sfEls.length; i++) {
        sfEls[i].onmouseover=function() {
            this.className+=" sfhover";
        }
        sfEls[i].onmouseout=function() {
            this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
        }
    }
}

var hwin = null;

function close_helper_window() {
    
    if (hwin && !hwin.closed) {
        hwin.close();
        hwin = null;
    }
    
}

function display_editor(id, on) {
    
    if ($('edit-box')) {
        
        // Check if we are just being asked to show edit-box and return
        if (on == true) {
            var s = new Effect.Appear('edit-box');
            return false;
        }
        
        var e = document.getElementById('binder-content');
        
        // Safari needs to have the child height set for some reason
        if (isSafari) {
            e = document.getElementById('media0');
        }
        
        if ($('edit-box').style.display == 'none') {
            
            if (e) {
                var h = e.offsetHeight;
                h = h - 200;
                h = (h < 10) ? 10 : h;
                e.style.height = h + 'px';
            }
            
            var s = new Effect.Appear('edit-box');
            
            // var params = "dependent=yes,menubar=no,status=no,toolbar=no,resizable=no,scrollbars=no,directories=no,toolbar=no,width=154,height=230";
            
            // hwin = window.open("/edit/helper", "helper", params);
            // if (hwin && !hwin.closed) {
            //   hwin.focus();
            // }
        }
        else {
            var s = new Effect.Fade('edit-box');
            
            if (e) {
                var h = e.offsetHeight;
                e.style.height = h + 200 + 'px';
            }
            
        }
    }
    
    return false;
}

function display_edit_toolbar(show) {
    
    if ($('edit_toolbar'))
        $('edit_toolbar').style.display = (show == true) ? 'block' : 'none';
}

var debug_mode = false;
var jmi_alert_timer = null;

function jmi_alert(str, pop_up, show_progress) {
    
    if (debug_mode != false)
        alert(str);
    
    else {
        if ($('status'))
            $('status').innerHTML = str;
    }

    // Update popup status div if requested
    if (pop_up == true) {

      if (jmi_alert_timer) {
        clearTimeout(jmi_alert_timer);
      }

      // Update status div with progress image
      if (show_progress)
        str = '<div>' + str + '<br /><img src="/images/loader.gif"></div>';

      $('binder-status').update(str);
      $('binder-status').style.display = "block";
      jmi_alert_timer = setTimeout("jmi_alert_clear()", 5000);
    }
}

function jmi_alert_clear() {
      $('binder-status').style.display='none'; 
      $('binder-status').innerHTML='';
      jmi_alert_timer = null;
}



// Set focus away and back to element - to fix IE bug
function give_me_focus(element) {
    this.focus();
    element.focus();
}

function is_enter_key(e) {
    var keynum = 0;
    
    // IE
    if (window.event) {
        keynum = e.keyCode
    }
    
    // Netscape/Firefox/Opera
    else if (e.which) {
        keynum = e.which
    }
    
    // Check if it is enter key
    return (keynum == 13);
}

function rate_binder(id, stars) {
    ajax_request("/shelf/rating", "id=" + id + "&stars=" + stars, rate_binder_cb);
    DisplayAlert('AlertBox',20,10);
}

function DisplayAlert(id,right,top) {
    document.getElementById(id).style.right=right+'px';
    document.getElementById(id).style.top=top+'px';
    document.getElementById(id).style.display='block';
}

function rate_binder_cb(originalRequest) {
    stars = originalRequest.responseText;
    apply_binder_rating(stars);
}

function apply_binder_rating(stars) {
    
    // Check if we've got any stars to set. If the user is not
    // logged in - they can not apply a rating and there is just
    // an image displayed
    if ($('one-star') == null)
        return;
    
    if (stars >= 1) {
        $('one-star').className = 'one-star-rating';
    }
    else {
        $('one-star').className = 'one-star';
        $('two-stars').className = 'two-stars';
        $('three-stars').className = 'three-stars';
        $('four-stars').className = 'four-stars';
        $('five-stars').className = 'five-stars';        
    }
    if (stars >= 2) {
        $('two-stars').className = 'two-star-rating';
    }
    else {
        $('two-stars').className = 'two-stars';
        $('three-stars').className = 'three-stars';
        $('four-stars').className = 'four-stars';
        $('five-stars').className = 'five-stars';                
    }
    if (stars >= 3) {
        $('three-stars').className = 'three-star-rating';
    }
    else {
        $('three-stars').className = 'three-stars';
        $('four-stars').className = 'four-stars';
        $('five-stars').className = 'five-stars';                        
    }
    if (stars >= 4) {
        $('four-stars').className = 'four-star-rating';
    }
    else {
        $('four-stars').className = 'four-stars';
        $('five-stars').className = 'five-stars';                                
    }
    if (stars >= 5) {
        $('five-stars').className = 'five-star-rating';
    }
    else {
        $('five-stars').className = 'five-stars';        
    }
    
}

function trim_str(str) {
    if (str)
        return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}


var lbi_binder_id = -1;

function set_working_binder_id(working_id) {
    lbi_binder_id = working_id;
}

function get_working_binder_id(working_id, fromparent) {
    
    if (working_id == -2) {
        
        var nbid = null;
        
        // See if we're being called from window that was opened
        if (fromparent == 1) {
            if (window.opener && !window.opener.closed)
                nbid = window.opener.document.getElementById('new_binder_id');
        }
        
        // Otherwise we're still in LiveBinderIt window
        else
            nbid = $('new_binder_id');
        
        // See if we got back a binder id
        if (nbid && (nbid.innerHTML != ''))
            lbi_binder_id = nbid.innerHTML;
        
        else
            lbi_binder_id = -2;
    }
    
    if (lbi_binder_id == -1) {
        lbi_binder_id = working_id;
    }
    
    return lbi_binder_id;
}

function edit_working_binder_id(working_id) {
    
    if (lbi_binder_id == -1) {
        lbi_binder_id = working_id;
    }
    
    if (lbi_binder_id != -1) {
        window.location = "/edit?id=" + lbi_binder_id;
    }
    
    return false;
}

// This routine parses the string that the LiveBinderIt 
// media/add_url dialog passes and updates the thumbnail
function update_working_binder(str, thumb, name, text_field) {
    vals = str.split(',');
    lbi_binder_id = vals[0];
    url = vals[1];
    $(thumb).src = url;
    $('select_tab').checked = "checked";
    $('tab_id').style.display = "none";
}

function get_tab_names(first_binder_id) {
    
    if (lbi_binder_id != -1)
        binder_id = lbi_binder_id;
    else
        binder_id = first_binder_id;
    
    if (binder_id != -1)
        ajax_request("/media/get_tabs_from_binder", 
            "id=" + binder_id, 
            set_tab_names_cb);
}
    
function set_tab_names_cb(originalRequest) {
        var tab_names = originalRequest.responseText;
        $('tab_select').innerHTML = tab_names;
}
    
    
// This routine does a simple assessment of the strength
// of a given password and sets the appropriate div
function passwordStrength(password) {

        
        var desc = new Array();
        desc[0] = "Very Weak";
        desc[1] = "Weak";
        desc[2] = "Better";
        desc[3] = "Medium";
        desc[4] = "Strong";
        desc[5] = "Strongest";
        
        var score = 0;
        
        //if password bigger than 6 give 1 point
        if (password.length > 6) score++;
        
        //if password has both lower and uppercase characters give 1 point      
        if ((password.match(/[a-z]/)) && (password.match(/[A-Z]/))) score++;
        
        //if password has at least one number give 1 point
        if (password.match(/\d+/)) score++;
        
        //if password has at least one special caracther give 1 point
        if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) score++;
        
        //if password bigger than 12 give another 1 point
        if (password.length > 12) score++;
        
        document.getElementById("passwordDescription").innerHTML = desc[score];
        document.getElementById("passwordStrength").className = "strength" + score;
}
    
function update_edit_menu(menu, submenu, mcolor, smcolor) {
        
        // Clear status line
        jmi_alert("");
        
        // Link Menu - if menu is 'link' display div and subtabs
        if ($('ed-link')) 
            $('ed-link').style.display = (menu == 'link') ? '' : 'none';
        
        if ($('et-link')) 
            $('et-link').style.backgroundColor = (menu == 'link') ? mcolor : '';
        
        if ($('es-link'))
            $('es-link').style.display = (menu == 'link') ? '' : 'none';
        
        // Tabs Menu - if menu is 'tabs' display div and subtabs
        if ($('ed-tabs'))
            $('ed-tabs').style.display = (menu == 'tabs') ? '' : 'none';
        
        if ($('et-tabs'))
            $('et-tabs').style.backgroundColor = (menu == 'tabs') ? mcolor : '';
        
        if ($('ed-tabs-add'))
            $('ed-tabs-add').style.display = (submenu == 'add') ? '' : 'none';
        
        if ($('es-tabs-add'))
            $('es-tabs-add').style.backgroundColor = (submenu == 'add') ? smcolor : '';
        
        if ($('ed-tabs-rename'))
            $('ed-tabs-rename').style.display = (submenu == 'rename') ? '' : 'none';
        
        if ($('es-tabs-rename'))
            $('es-tabs-rename').style.backgroundColor = (submenu == 'rename') ? smcolor : '';
        
        if ($('ed-tabs-move'))
            $('ed-tabs-move').style.display = (submenu == 'move') ? '' : 'none';
        
        if ($('es-tabs-move'))
            $('es-tabs-move').style.backgroundColor = (submenu == 'move') ? smcolor : '';
        
        if ($('es-tabs'))
            $('es-tabs').style.display = (menu == 'tabs') ? '' : 'none';
        
        // Search Menu - if menu is 'search' display div and subtabs
        if ($('ed-search'))
            $('ed-search').style.display = (menu == 'search') ? '' : 'none';
        
        if ($('et-search'))
            $('et-search').style.backgroundColor = (menu == 'search') ? mcolor : '';
        
        if ($('es-search-flickr'))
            $('es-search-flickr').style.backgroundColor = (submenu == 'flickr') ? smcolor : '';
        
        if ($('es-search-youtube'))
            $('es-search-youtube').style.backgroundColor = (submenu == 'youtube') ? smcolor : '';
        
        if ($('es-search-delic'))
            $('es-search-delic').style.backgroundColor = (submenu == 'delic') ? smcolor : '';
        
        if ($('es-search-collect'))
            $('es-search-collect').style.backgroundColor = (submenu == 'collect') ? smcolor : '';
        
        if ($('es-search'))
            $('es-search').style.display = (menu == 'search') ? '' : 'none';
        
        // Layout Menu
        if ($('ed-layout'))
            $('ed-layout').style.display = (menu == 'layout') ? '' : 'none';
        
        if ($('et-layout')) 
            $('et-layout').style.backgroundColor = (menu == 'layout') ? mcolor : '';
        
        if ($('es-layout'))
            $('es-layout').style.display = (menu == 'layout') ? '' : 'none';
        
        // Font Menu
        if ($('ed-text'))
            $('ed-text').style.display = (menu == 'text') ? '' : 'none';
        
        if ($('et-text'))
            $('et-text').style.backgroundColor = (menu == 'text') ? mcolor : '';
        
        // Properties Menu
        if ($('ed-props'))
            $('ed-props').style.display = ((menu != 'search') && (menu != 'layout') && (menu!= 'link')) ? '' : 'none';
        
        if ($('et-props'))
            $('et-props').style.backgroundColor = (menu == 'properties') ? mcolor : '';
        
        if ($('ed-props-desc'))
            $('ed-props-desc').style.display = (menu == 'properties') ? '' : 'none';
        
        if ($('es-props'))
            $('es-props').style.display = (menu == 'properties') ? '' : 'none';
        
        return false;
}
    
function addJavascript(jsname) {
        var th = document.getElementsByTagName('head')[0];
        var s = document.createElement('script');
        s.setAttribute('type','text/javascript');
        s.setAttribute('src',jsname);
        th.appendChild(s);
} 
    
    
var myEditor = null;
    
function showEditor() {
        if (myEditor == null) {
            
            myEditor = new YAHOO.widget.SimpleEditor('msgpost', 
                { height: '100%', width: '100%', dompath: true } ); 
            myEditor.render(); 
        }
        
        else {
            myEditor.show(); 
        }
}
    
function hideEditor() {
        myEditor.hide();
}
    
function show_helper () {
        var popup = document.getElementById ("helper-menu");
        popup.style.visibility = "visible";
        
}
    
function deselectTabs() {

        var sel = bdr.getSelectedTab();    
        $('tabx-'+sel).innerHTML = printf(unselectedTabHTML_d_d_s, sel, sel, bdr.tabNameAt(sel));
        
        $('binder-subtab-pane').innerHTML = "&nbsp;";
        $('binder-lead-in').innerHTML = "&nbsp;";
}
    

function cleanWordHTML(str) {

  str = str.replace(/<o:p>\s*<\/o:p>/g, "") ;
  str = str.replace(/<o:p>.*?<\/o:p>/g, "&nbsp;") ;
  str = str.replace( /\s*mso-[^:]+:[^;"]+;?/gi, "" ) ;
  str = str.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, "" ) ;
  str = str.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"" ) ;
  str = str.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, "" ) ;
  str = str.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"" ) ;
  str = str.replace( /\s*TEXT-ALIGN: [^\s;]+;?"/gi, "\"" ) ;
  str = str.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"" ) ;
  str = str.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ) ;
  str = str.replace( /\s*tab-stops:[^;"]*;?/gi, "" ) ;
  str = str.replace( /\s*tab-stops:[^"]*/gi, "" ) ;
  str = str.replace( /\s*face="[^"]*"/gi, "" ) ;
  str = str.replace( /\s*face=[^ >]*/gi, "" ) ;
  // str = str.replace( /\s*FONT-FAMILY:[^;"]*;?/gi, "" ) ;
  // str = str.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;
  // str = str.replace( /<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, "<$1$3" ) ;
  // str = str.replace( /\s*style="\s*"/gi, '' ) ; 
  str = str.replace( /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;' ) ; 
  str = str.replace( /<SPAN\s*[^>]*><\/SPAN>/gi, '' ) ; 
  str = str.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ; 
  str = str.replace( /<SPAN\s*>(.*?)<\/SPAN>/gi, '$1' ) ; 
  // str = str.replace( /<FONT\s*>(.*?)<\/FONT>/gi, '$1' ) ;
  str = str.replace(/<\\?\?xml[^>]*>/gi, "") ; 
  str = str.replace(/<\/?\w+:[^>]*>/gi, "") ; 
  str = str.replace( /<H\d>\s*<\/H\d>/gi, '' ) ;
  str = str.replace( /<H1([^>]*)>/gi, '' ) ;
  str = str.replace( /<H2([^>]*)>/gi, '' ) ;
  str = str.replace( /<H3([^>]*)>/gi, '' ) ;
  str = str.replace( /<H4([^>]*)>/gi, '' ) ;
  str = str.replace( /<H5([^>]*)>/gi, '' ) ;
  str = str.replace( /<H6([^>]*)>/gi, '' ) ;
  str = str.replace( /<\/H\d>/gi, '<br>' ) ; //remove this to take out breaks where Heading tags were 
  str = str.replace( /<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;' ) ;
  str = str.replace( /<(B|b)>&nbsp;<\/\b|B>/g, '' ) ;
  str = str.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
  str = str.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
  str = str.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;

  //some RegEx code for the picky browsers
  // var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)","gi") ;
  //str = str.replace( re, "<div$2</div>" ) ;
  //var re2 = new RegExp("(<font|<FONT)([^*>]*>.*?)(<\/FONT>|<\/font>)","gi") ; 
  //str = str.replace( re2, "<div$2</div>") ;
  //str = str.replace( /size|SIZE = ([\d]{1})/g, '' ) ;

  return str ;
}


function getComputedWidth(e) {

  var w = 0;

  if (isIE) {
    w = $(e).offsetWidth;
  }

  else {

    var docObj = $(e);
    w = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("width");
    w = w.split('px');
    w = w[0];
  }

  return w;
}

function show_uploaded_binders(originalRequest) {

    $('upload_binders').innerHTML = originalRequest.responseText;

    // Grab correct row # from response
    var myrow = originalRequest.responseText.substr(5,4);

    var i = myrow - 0;
    var current_row = $('filemgr_row_'+i);
    current_row.innerHTML = originalRequest.responseText;
    var s = new Effect.Appear(current_row);

    var fname = $('upload_file_name').innerHTML;
    var nb = $('upload_total_binders').innerHTML;
    $('upload_for_file').innerHTML = nb + " binder(s) found with: <b>" + fname + "</b>";
}

function show_uploaded_files(originalRequest) {
    $('upload_medias').innerHTML = originalRequest.responseText;

    var fsize = $('upload_file_size').innerHTML / 1024 / 1024;
    fsize = round(fsize);
    var fnum = $('upload_total_files').innerHTML;
    $('upload_kb').innerHTML = fnum + " Files - Total Size: "+addCommas(fsize,1)+"MB";
}

function update_uploaded_files(originalRequest) {
    show_uploaded_files(originalRequest);
    $('upload_binders').innerHTML = "";
    $('upload_for_file').innerHTML = "";
}

function addCommas(nStr,decimals) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + ((decimals) ? x2 : "");
}

function round(num) {
  num = num.toString();
  var split = num.split(".");
  var dec = split[1].substr(0,3);
  var dec1 = dec.match(/\d{2,2}/);
  var dec2 = dec.match(/(\d$)/);
  var rounded = (dec1 + "." + dec2[0]);
  return split[0] + "." + Math.round(rounded);
}

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
