/* + +++
  * *********************************************************************
  * *********************************************************************
  * ***
  * ***  Copyright (C) 2003-05   Mirra, Inc.
  * ***  All rights reserved.
  * ***
  * ***  No part of this software, in source or object code form, may
  * ***  be modified, compiled, decompiled, redistributed, stored in
  * ***  a retrieval system, or transmitted in any form or by any means,
  * ***  electronic, mechanical, photocopying, recording or otherwise,
  * ***  without the prior written consent of Mirra, Inc.
  * ***
  * ***  Ispiri and Mirra are registered trademarks of Mirra, Inc.
  * ***
  * *********************************************************************
  * *********************************************************************
  - ___ */

/*<%--
  -- common utility functions
  --%>*/

function uiutil_comp(a,b)
{
    for (var i = 0 ; i < a.length && i < b.length; i++) 
    {
        t1 = a.charAt(i);
        t2 = b.charAt(i);
        if (t1 > t2) return 1;
        else if (t1 < t2) return -1;
    }
    return 0;
}

function uiutil_comp_booleans(isMyMirra1, isMyMirra2)
{
    if (isMyMirra1 == true && isMyMirra2 == true) 
        return 0;
    else if (isMyMirra1 == true)
        return -1;
    else
        return 1;
}

function nocase_sortname(a, b)
{
    var a_val;
    var b_val;
    a_val = a.name.toLowerCase();
    b_val = b.name.toLowerCase();
    return uiutil_comp(a_val,b_val);
}

function sort_my_mirra(a, b)
{
    return uiutil_comp_booleans(a.myMirra, b.myMirra);
}

function sort_client_owner(a, b)
{
    // first sort by ownership
    testone = uiutil_comp_booleans(a.hasUserFolder, b.hasUserFolder);
    if (testone != 0)
        return testone;
    
    // then sort by alpha
    return nocase_sortname(a, b);
}

// currently not use, might need it later on, this function is to make sure all 
// owner's mirras are placed to the top of the array so that we can always 
// display owner's mirras on top of the list

function rearrange_mirra_array(mirras)
{
    var new_mirras = new Array();
    for (var a = 0; a < mirras.length; a++)
    {
        if (mirras[a].myMirra == true)
            new_mirras.unshift(mirras[a]);
        else
            new_mirras[new_mirras.length]=mirras[a];
    }

    return new_mirras;
}

//
// Common CSS content elements
//

function BGPanel_startPane()
{
    var ss = "<div class='MOW_Container1'><div class='MOW_Container1_Top'></div><div class='MOW_Container1_Middle'>";
    document.write(ss);
}

function BGPanel_endPane()
{
	var ss = "</div class='MOW_Container1_Middle'><div class='MOW_Container1_Bottom'></div></div class='MOW_Container1'>";
    document.write(ss);
}

function BGPanel_startAlternatePane()
{
    var ss = "<div class='MOW_Container2'><div class='MOW_Container2_Top'></div><div class='MOW_Container2_Middle'>";
    document.write(ss);
}

function BGPanel_endAlternatePane()
{
	var ss = "</div class='MOW_Container2_Middle'><div class='MOW_Container2_Bottom'></div></div class='MOW_Container2'>";
    document.write(ss);
}

function BGPanel_AddSpacer()
{
    document.write("<div class='backupMirraSpacer'></div>");
}

function BGPanel_AddShareFolderSpacer()
{
    document.write("<div class='shareFolderSpacer'></div>");
}


//	controlLabelClick(event, elementId)
//
//	This routine enables the click of a control label to be the same as a click
//	on the control itself.  It works for radio buttons and checkboxes.
//
//	To use:
//
//		1) create your radio button/checkbox as normal, but be sure 
//			to give it a unique id within your page:
//				<input type="checkbox" id="myUniqueControl" onClick="someMethod()">
//
//		2) Create a label inside a DIV or TD next to it, and set the onclick
//			of the label element to call controlLabelClick():
//				<div ... onclick="controlLabelClick(event, 'myUniqueControl')" ...
//					>Label Text Here</div>
//
//			You may want to give the label a css class with cursor:hand to indicate
//			that it's clickable.
//
//	
//		That's it!  Note that your onClick routine in your checkbox, etc. must not
//		depend on the fact that it was explicitly clicked -- eg: you should not
//		depend on event.target being your checkbox, as the link may have actually
//		received the click.
//
function controlLabelClick(evt, elementId) {
	if (evt == null) evt = window.event;
	var event = evt;
	
	var element = document.getElementById(elementId);
	if (element == null) return;
	
	if (element.disabled) return;
	
	var type = element.type;
	if (type == "radio") {
		element.checked = true;
	
	} else if (type == "checkbox") {
		element.checked = !element.checked;
	}
	var script = ""+element.onclick;
	script = script.substring(script.indexOf("{")+1, script.lastIndexOf("}"));
	eval(script);
}

//
// Generic function to replace existing page content
//

function replaceSpanHTML(span, newHTML)
{
    var oldHTML = "";
    if (newHTML != "")
    {
        status_doc = document;
        if (status_doc)
        {
            var span = status_doc.getElementById(span);
            if (span)
            {
                oldHTML = span.innerHTML;
                span.innerHTML = newHTML;
            }
        }
	}
	
	return oldHTML;
}

//
// Cookie management used to make the UI sticky for certain settings
//

function getCookie(name)
{
    var cookies = document.cookie;
    var offset = cookies.indexOf(name + "=");
    
    if (offset == -1)
        return null;
    
    offset = offset + name.length + 1;
    
    var endoffset = cookies.indexOf(";", offset);
    if (endoffset == -1)
        endoffset = cookies.length;
    
    var result = cookies.substring(offset, endoffset);
    return unescape(result);
}

function setSessionCookie(name, value)
{
    document.cookie = name + "=" + escape(value);
}

function setOneYearCookie(name, value)
{
    var today = new Date();
    var expires = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000); // one year
    document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString();;
}

function deleteCookie(name)
{
    document.cookie = name + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//	StringBuffer class
//
//	This class creates an efficient string buffer that you can use 
//	to do concatenation of HTML much quicker than the standard "a"+"b" method.
//
//	To use:
//
//		1) Create a new StringBuffer
//				var SB = new StringBuffer()
//
//		2) Call "append()" with as many arguments (and as many times) as you want
//				SB.append("some text");
//				if (it.isTrue) SB.append("other text");
//				SB.append( (a==b ? "a" : "b") );
//
//		3) When you want the value of the buffer, do a toString():
//				return SB.toString()
//			or call some method that coerces it to call its toString automatically, eg:
//				alert(SB)
//
//	OR, to call as a one-off (without creating an object), use
//			var myVar = StringBuffer.concat("a","b","c");
//

function StringBuffer() {
	this.reset();
}
StringBuffer.prototype.append = function SB_append() {
	// special case for single argument, a bit faster
	if (arguments.length == 1) {
		this.buffer[this.buffer.length] = arguments[0];
	} else {
		// note: in some browsers, the "arguments" array doesn't have a join command
		if (arguments.join == null) arguments.join = this.buffer.join;
		this.buffer[this.buffer.length] = arguments.join("");
	}
	
	// don't go over 50 elements in the main buffer
	if (this.buffer.length > 100) this.buffer = [this.buffer.join("")];
}
StringBuffer.prototype.toString = function SB_toString() {
	return this.buffer.join("");
}
StringBuffer.prototype.reset = function SB_reset() {
	this.buffer = [];
}
StringBuffer.concat = function SB_concat() {
	// note: in some browsers, the "arguments" array doesn't have a join command
	if (arguments.join == null) arguments.join = [].join;
	return arguments.join("");	
}

function getBaseFileName(fileName)
{
	var pathSep = findPathSeparator();
	var fname   = fileName;
	var i       = fname.indexOf(pathSep);
	while (i > -1) {
		fname = fname.substring(i + 1);
		i = fname.indexOf(pathSep);
	}
	return fname;
}

function findPathSeparator()
{
	var browseString = navigator.userAgent.toLowerCase();
	var separator;

	if      (browseString.indexOf('win')       > -1) separator = "\\";
    // somehow HTML file chooser returned path uses / insteaed of : for Mac
	//else if (browseString.indexOf('mac')       > -1) separator = ":" 
	else if (browseString.indexOf('mac')       > -1) separator = "/"
	else if (browseString.indexOf('x11')       > -1) separator = "/";
	else if (browseString.indexOf('linux')     > -1) separator = "/";
	else if (browseString.indexOf('konqueror') > -1) separator = "/";
	else separator = "\\"; // windows then
	return separator;
}

function findBrowserOS()
{
	var browseString = navigator.userAgent.toLowerCase();
	var OS;

	if      (browseString.indexOf('win')       > -1) OS = "Windows";
	else if (browseString.indexOf('mac')       > -1) OS = "Mac";
	else if (browseString.indexOf('x11')       > -1) OS = "Unix";
	else if (browseString.indexOf('linux')     > -1) OS = "Linux";
	else if (browseString.indexOf('konqueror') > -1) OS = "Linux";
	else OS = "an unknown operating system";
}

var	onlineHelpPath = "/dyn/help/";
var helpFileListLoaded = false;
var helpFileList = new Object();
var helpFileDefault = "/dyn/help/index.html";

//
// in order to auto locate the help file from a JSP page, setup help files here:
// for each help file that should be invoked from a JSP
// 1) name the help file to mirror JSP file name with .html ext;
//    for example, shares.jsp vs shares.html
// 2) add one line of code here to add help file name, pass in JSP bse file name
//    for example, addHelpFile("confirmRemoveShares")
//
if (helpFileListLoaded == false)
{
    addHelpFile("addFiles");
    addHelpFile("ca");
    addHelpFile("confirmRemoveShares");
    addHelpFile("details");
    addHelpFile("downloadZIP");
    addHelpFile("manageShare");
    addHelpFile("previewImage");
    addHelpFile("remote");
    addHelpFile("saveFile");
    addHelpFile("settings");
    addHelpFile("shares");
    addHelpFile("signin");
    addHelpFile("viewFiles");
    helpFileListLoaded = true;
}

function addHelpFile(jspBaseName)
{
    var helpUrl = onlineHelpPath + jspBaseName + ".html";
	helpFileList[jspBaseName] = helpUrl;
}

function onHelpButtonClick(helpFileName)
{
    var url;
    if (helpFileName)
    {
        url = onlineHelpPath + helpFileName;
        mirraHelpWindow = window.open(url, "help_window", "status=no,toolbar=no,scrollbars=yes,resizable=yes,width=800,height=600");
        mirraHelpWindow.focus();
    }
    else
    {
        var jspBaseName = findLocationPageBaseName();
        url = helpFileList[jspBaseName];
        if (url)
        {
            mirraHelpWindow = window.open(url, "help_window", "status=no,toolbar=no,scrollbars=yes,resizable=yes,width=800,height=600");
            mirraHelpWindow.focus();
        }
        else
        {
            mirraHelpWindow = window.open(helpFileDefault, "help_window", "status=no,toolbar=no,scrollbars=yes,resizable=yes,width=800,height=600");
            mirraHelpWindow.focus();
        }
    }
    return false;
}

//  findLocationPage()
//
//  parse the current location and extracts the page
//
function findLocationPage() {
    var url = location.href;
    var lastSlash = 0;
    var offset = 0;
    
    do {
        lastSlash = offset;
        offset = url.indexOf("/", offset);
    } while (offset++ != -1);
    
   
    if (lastSlash == 0)
    {
        return "";
    }
    else
    {
        return url.substring(lastSlash, url.length);
    }
}

function findLocationPageBaseName()
{
    var pageName = findLocationPage();
    if (pageName)
    {
        var offset = pageName.indexOf(".");
        if (offset == -1)
        {
            return pageName;
        }
        else
        {
            return pageName.substring(0, offset);
        }
    }
    else 
    {
        return "";
    }
}

// function abbreviate a name to max length
function truncateName(name, maxLength)
{
	var shortname = name;
	var namelength = name.length;
	
	if (namelength > maxLength)
	{
        var halfLen = (maxLength - 3) / 2;
		shortname = name.substring(0,  halfLen) + "..." + name.substring(namelength -  halfLen, namelength);
	}
	
	return shortname;
}

function errorPopupWindow(url)
{       
    mirraErrorPopupWindow = window.open(url, "", "width=400,height=300");
	mirraErrorPopupWindow.focus();
	return false;
}

function trimString(str)
{
    str =  str.replace(/^\s+/g, ""); // strip leading
    return str.replace(/\s+$/g, ""); // strip trailing
}

function containWhiteSpace(text)
{
    if (text == null || text.length == 0)
    {
        return false;
    }
    for (var i = 0; i < text.length; i++)
    {
        var c = text.charAt (i);
        switch (c)
        {
        case ' ':
            return true;
        case '\t':
            return true;
        case '\n':
            return true;
        }
    }
    return false;
}