


/******************************************************************************************
         vyewBaseLib.js
 ******************************************************************************************/

/** 
 * 	vyewBaseLib.js - Supports the main vyew frameset,
 * 	which is either /room.php, or /rdev.php, etc...
 *	Coypright (c)2003-2008 Vyew, Simulat, Inc 
 *
 *  @Includes cookie utilities
 */

appStartTime = new Date().getTime();


/** 
 * Redirect if different version
 */
function chkVyewVersion()
{
       var mtg=urlSegment("#")+'';
       var vers=getVers();
       try{
       if(mtg && mtg.length>1){
               var url='/'+vers+'/go/ajax.login.php';
               $.post(url,{myaction:'chkversion',mtg:mtg}, function(res)
               {
                       var res=res+'';
                       if(res && res.length>3 && res.match(/^\//)) top.location=res;
               });
       }
       }catch(e){}
}



/* 
 * -----------------------------------------------------------------
 * 	Frame Utils - for opening and closing ajax frame
 * ----------------------------------------------------------------- 
 */

/**
 * If top_url = "same"1, then show what is there already,
 * if top_url = "main", then show the main frame at the top
 * todo: top_url could also be a web address 
 * todo: check if what they call is already set then disregard...?
 *       or do that for openmyhome
 * @param main_url {optional} - 
 * @param top_url {optional} -
 * @param top_height {optional} -
 */
function openFrame(main_url,top_url,top_height)
{
	if(top_height==null) top_height=43;
  	var rw = getFramesetHeight();               //rw:0,*,0,0
	var pl = rw.indexOf(",");					//get first ,
	if(top_url=="main")
		rw=rw.substr(0,pl)+","+top_height+",0,*";	//rw:n,top_height,0,*
	else
		rw=rw.substr(0,pl)+",0,"+top_height+",*";	//rw:n,0,top_height,*
	setFramesetHeight(rw);
	if(typeof main_url == "string" && main_url.length > 4) 
		document.getElementById("botframe").src=main_url;
	if(typeof top_url == "string" && top_url.length > 4)
		document.getElementById("midframe").src=top_url;
    //document.getElementsByTagName("frameset")[0].rows = "0,43,*";
}

var lastcfCall=0;
function closeFrame()
{
return;
	main.$(main.getMovie('sm_main')).css('height','100%')
	main.$('.myHomeBox').hide();
	return;
	
	//old
    var rw = $("#frameset1").attr("rows");
    var pl = rw.indexOf(",");
    rw = rw.substr(0,pl)+",*,0,0";
    $("#frameset1").attr("rows",rw);
    //document.getElementsByTagName("frameset")[0].rows = "*,0,0";
}
var closeImageEditor=closeFrame;


/**
 * Opens the ajax version of "my home"
 * @param tabID {string} - "myvyewbooks" (default), "myfiles", "settings"
 * @param sectionID
 */
function openMyHome(tabID,sectionID)
{
//nf
	return main.openMyHome(tabID,sectionID);

	//---disregard if the bottomframe is already maximized
	var myhomeTopOffset=62;
	var rowset = $("#frameset1").attr("rows");
	if(rowset.substr(-1)=="*") return;
	sectionID=(sectionID==null)?"":sectionID;
	tabID=(tabID)?tabID:"";
	bfu=document.getElementById("botframe").src	
	if(bfu.indexOf('myhome.html')>-1){
		openFrame(null,'main',myhomeTopOffset);
	}else{
		var url='/'+vers+'/content/myhome.html#'+tabID;
		openFrame(url,'main',myhomeTopOffset);
	}

	if(botframe && botframe.gMsg) botframe.gMsg.fireEvent('onActivateMyHome');

	//--- redraw ui to fix a bug where the whole myhome ui gets shifted out of the frame
	if($ && $.browser && $.browser.mozilla){
		tryRedrawUI();
	}
}

/**
 * Attempts to redraw myhome UI, if myhome not loaded yet, tried again later
 */
function tryRedrawUI(recurs){
	var now=new Date().getTime();
	if(now-appStartTime < 2000) return;
	dbg('try redraw ui');
	recurs = (null) ? 1 : recurs+1; 
	if(recurs>10) return;
	if(botframe && botframe.ma && botframe.ma.vyewport && botframe.ma.vyewport.disable){
		botframe.ma.vyewport.disable();
		setTimeout('botframe.ma.vyewport.enable();',100);
	}else{
		//most likely it doesnt exist because its not loaded yet, so wait
		setTimeout('tryRedrawUI('+recurs+');', 200);
	}
}	
	
/**
 * return ref to main flash frame
 */
function getMainFrame(){ return window.main; }
function getmyhome(){ return window.main.getmyhome(); }

/**
 * Picnic image editor
 * Todo: make sure this is still compatible, now that new ajax frame stuff is in
 */
function openImageEditor(url){
	openFrame(url,1,43);
}




/**
 * ------------------------------------------------------------------
 *  MISCELLANEOUS
 * ------------------------------------------------------------------
 */

function empty(v){
  if(typeof v == "undefined" || v==null || v==undefined) return true;
  else return false;
}
function isDefined(obj){
    return !empty(obj);
}


function hasFirebug()
{
	try{
    if(typeof console == "undefined"){
        if(!window.loadFirebugConsole) return false;
        else window.loadFirebugConsole();
    }
    if(typeof console != "undefined" && console.debug) return true;
    return false;
	}catch(e){ return false; }
}

function dbg()
{
    if (!hasFirebug()) return;
    var out="";
    for(var i=0;i<arguments.length;i++){ out+=arguments[i]+", "; }
    out=out.substr(0,out.length-2);
    console.debug(out);
}

function dbd(x,txt)
{
    if (!hasFirebug()) return;
    if(txt) console.debug('---------------- '+txt);
    else console.debug('----------------');
    console.dir(x);
}

function isNumeric(n){
  sn=new String(n);
  if(sn.match(/^[0-9]*$/)) return true;
  else return false;
}
function isNaN(n){ return !isNumeric(n) }



/**
 * Used during live version releases - check if meeting room is active
 * by querying against the /maintenance/activerooms.txt list
 * @return {boolean}
 */
function isRoomActive(callback)
{
	//if(typeof ira_iscalling != "undefined"){ if(ira_iscalling==true) return; }
	ira_iscalling=true;
	ira_callback=callback;
	var h=''+top.document.location.hash;
	h=h.replace(/^\s+|\s+$/g,"");           //trim
	if(h.substr(0,1)=="#")h=h.substr(1);
	if(h.substr(0,1)=="/")h=h.substr(1);
	if(h.substr(-1)=="/")h=h.substr(0,h.length-1);
	h=h.replace(/\//,"_");
	if( !(h.length>2) ) return;
	//check if has characters (need to lookup numeric meeting id)
	$.post('/site/ajax.roomisactive.php',{id:h}, function(res)
	{
		ira_iscalling=false;
		if(typeof res != "undefined"){
			if(res=="true" || res==true)
				ira_callback.apply(this,[true]);
			else
				ira_callback.apply(this,[false]);
		}else{
			ira_callback.apply(this,[false]);
		}
	});
}



/**
 * ---------------------------------------------------------------------------
 * COOKIE LIBRARY: (also provides support for flash cookie setter/getter)
 *      getCookie(cookieName)
 *      setCookie(cookieName, value)
 *
 * FLASH INSTRUCTIONS:
 *       1. copy cookieLib.js (or vyewLib) to the same place as your .html file which references your .swf
 *       2. put this lines in your .html file :
 *       ---------------------------------------------------------------------------
 *           <script src="cookieLib.js" type="text/javascript"></script>
 *       ---------------------------------------------------------------------------
 * SET A COOKIE FROM FLASH:
 *            import flash.external.*;
 *            ExternalInterface.call("fs_setCookie", "cookieName", "cookieValue", "EXPIRATION");
 *
 *            (expiration can be: "never", or "session" or a "number" representing minutes)
 *            (default expiration is "never")
 *            (session expires when the browser is closed)
 *           (minutes= "60" for 1 hour, "1440" for 1 day, etc...)
 *
 * RETRIEVE A COOKIE FROM FLASH:
 *           import flash.external.*;
 *          var cookievalue = ExternalInterface.call("fs_getCookie", "cookieName");
 *
 * ------------------------------------------------------------------
 */

function fs_getAllCookies(){
    return document.cookie;
}

/**
 * Retrieves a cookie, converts to json if passed
 * @param a {string} - cookie name
 * @param isJson {bool} - if true, object will be converted from JSON string to object
 */
function getCookie(a,isJson){
    var e
    var m=" "+document.cookie+";"
    var N=" "+a+"=",s=m.indexOf(N),r="";
    if(s!=-1){s+=N.length;e=m.indexOf(";",s);r=unescape(m.substring(s,e))}
    if(r.match(/ckjson.:1/) || r.match(/ckjson:1/) || isJson==true){
        try {
            r=JSON.decode(r);
            delete r.ckjson;
        }catch(e){ throw 'Err394x:Converting JSON' }
    }
    if(r=="false") r=false;
    return r
}

function clearCookie(n){
    var e=new Date();
    e.setTime(e.getTime()-20000000);
    document.cookie=n+"=0; path=/; expires="+e.toGMTString() + "; domain="+fs_getHostname();
    document.cookie=n+"=0; path=/; expires="+e.toGMTString() + ";";
}

/**
 * Set a cookie (alias fore setCookie())
 * NEW: if value is a complex object/array, it will be json'd and unjson'd automatically on getCookie()
 * @param varName - cookie name
 * @param varVal - value to be set
 * @param exp - expiration in minutes, or set to "session", or "never"
 * @param allSubDomains - boolean: set true if you want to set to ".domain.com"
 *                      which will make cookie available to all subdomains
 */
function setCookie(varName,varVal,exp,allSubDomains){
    varVal=(varVal==null)?'0':varVal
    if(typeof(varVal)!="string" && typeof(varVal)!="number"){
        varVal.ckjson=1;
        varVal=JSON.encode(varVal);
    }
    var e=new Date();
    if(typeof(exp)=="undefined" || exp=="null" || exp==null || exp=="" || exp=="session"){
        exp=";";
    }else if (exp=="never"||exp=="forever")
    {
        e.setFullYear(e.getFullYear() + 10);
        e.toGMTString();
        exp="; expires=" + e;
    }else{
        e.setTime(e.getTime()+(60000*exp))
        e.toGMTString();
        exp="; expires=" + e
    }
    var ck = varName+"=" + varVal + "; path=/;" + exp;
    if(allSubDomains==true) ck += " domain="+fs_getHostname()+";";
    document.cookie = ck;
    return "1";
}

/**
 * Returns the hostname of current url:
 * ie. if url is www.domain.com/abc/dev, returns: domain.com
 */
function getHostname()
{
    var h=document.location.host;
    var p=h.lastIndexOf('.');
    p=h.lastIndexOf('.',p-1);
    if (p>-1) h=h.substr(p+1);
    return h;
}
var fs_clearCookie=clearCookie;
var fs_getHostname=getHostname;
var fs_setCookie=setCookie;
var fs_getCookie=getCookie;

/**
 * Records all vyew cookies, clears them, then re-sets them
 * this is to clear out the global subdomain cookies (.domain.com)
 */
function resetVyewCookies(){
    var sid=getCookie("sid");
    var lID=getCookie("lID");
    var kli=getCookie("keepLoggedIn");
    clearCookie("sid"); clearCookie("lID"); clearCookie("keepLoggedIn");
    setCookie("sid",sid);
    if(lID && kli) setCookie("lID", lID, "forever");
    if(kli) setCookie("keepLoggedIn", kli, "forever");
}

//get myhome
function gmg(){
	return main.frames['myHomeBox'];
}



/**
 * Given a url: http://domain.com/content/product/uses?a=1&b=2#hello
 * Examples:
 *             urlSegment(0) = "content"
 *     urlSegment(1) = "product"
 *     urlSegment("#") = "hello"
 *             urlSegment("?") = "a=1&b=2#hello"
 *     urlSegment("?a") = "1"
 *     urlSegment("?b") = "2"
 *             urlSegment("domain") = "domain.com"
 *             urlSegment("base") = "http://domain.com/content/product/uses"
 *             urlSegment("baserel") = /content/product/uses"
 *
 * TO SET THE URL HASH:
 *             top.location.hash = "abc"
 */
function urlSegment(num, win)
{
       if(!win) win=this;
       try{
    var loc=win.location.href.match(/\/\/(.*)/)[1];
       }catch(e){ return ""; }
    if (!loc) return "";
    if(!isNaN(num)){
               segs=loc.split("/");
        return segs[num+1];
    }else if(num=="#"){
        pl=loc.indexOf("#");
        if(pl==-1)return "";
        else {
            loc=loc.substr(pl+1);
            pl=loc.indexOf("?");
            if(pl==-1) return loc;
            else return loc.substr(0,loc.indexOf("?"));
        }
    }else if(num=="?"){
        pl=loc.indexOf("?");
        if(pl==-1)return "";
        else return loc.substr(pl+1);
    //check if "?variable"
    }else if(num.substr(0,1)=="?"){
        var getv=num.substr(1);
        if(loc.indexOf(getv)==-1) return '';
        pl=loc.indexOf("?");
        if(pl==-1) return "";
        var q=''+loc.substr(pl+1);
        if(q.indexOf(getv)==-1 || typeof q != "string") return '';
        var regx=new RegExp(getv+"=([^&#]*)");
        var res=q.match(regx)[1];
        return res;
    }else if(num=="domain"){
               return loc.match(/(.*?)\//)[1]
       }else if(num=="base"){
               var loc=win.location.href;
               pl=loc.indexOf("?");
               if(pl>=0) loc=loc.substr(0,pl);
               pl=loc.indexOf("#");
               if(pl>=0) loc=loc.substr(0,pl);
               return loc;
       }else if(num=="baserel"){
        var loc=win.location.href.match(/^.*?\/\/.*?(\/.*)/)[1];
        pl=loc.indexOf("?");
        if(pl>=0) loc=loc.substr(0,pl);
        pl=loc.indexOf("#");
        if(pl>=0) loc=loc.substr(0,pl);
        return loc;
    }

    return "";
}



function getVers()
{
       try{
        var auto_vers="v3.83";
        if(!auto_vers.match(/^v[0-9]+\.[0-9]+[^/]*/))
            auto_vers=document.location.href.match(/\/(v[0-9]+\.[0-9]+[^/]*)\//)[1];
        if(auto_vers.match(/^v[0-9]+\.[0-9]+[^/]*/)) return auto_vers;
    }catch(e){}
       try{ 
               var default_vers=top.vers; 
        if(default_vers.match(/^v[0-9]+\.[0-9]+[^/]*/)) return defaul_vers;
       }catch(e){}
       dbg("WARNING:334 - couldnt autodetect vyew version");
       return "vlatest";       
}



