


/******************************************************************************************
         vyewLib.js
 ******************************************************************************************/

/**
 * vyewLib.js 
 * Vyew Javascript Library 
 * Copyright (c)2007-2008 Vyew, Simulat, Inc.
 *
 * @author timh@vyew dot com
 *
 * DEPENDANCIES:
 * -------------
 * 		jquery.js
 *		vyew.phpobject.js
 *
 * INCLUDES:
 * ---------
 *		- cookie lib functions
 * 		- login checks
 *
 * CHANGES:
 *		8/29/08 - changed to depend on vyew.phpobject.js for calling json gateway instead of siteajax.php
 *
 * TODO:
 *		- handle multiple ajax calls ?? is this still relevant?
 */


//--- Setup package
if(typeof vyew=="undefined") vyew=new Object();
if(!vyew.ud) vyew.ud=new Object();
if(!vyew.od) vyew.od=new Object();
vyew.whoami="vyew object";

//make sure vyew.phpobject is loaded
if(!vyew.php || vyew.php == undefined){
	try{
        var auto_vers="v4.25";
        if(!auto_vers.match(/\/(v[0-9]+\.[0-9]+[^/]*)(\/)/))
            auto_vers=document.location.href.match(/\/(v[0-9]+\.[0-9]+[^/]*)(\/)/)[1];
		else auto_vers=""
    }catch(e){}
	if(empty(auto_vers)){ 
		dbg("No detection: vyewLib-auto_vers");
		auto_vers="vlatest";
	}
	try{ $.getScript("/"+auto_vers+"/js/vyew.phpobject.js"); }catch(e){ dbg('Cant Load vyew.phpobject.js');}
}


/**
 * Checks if user data is present (reg'd user). Doesn't verify it, only that it exists
 *
 * @param callback - a function to be called back with results object
 * @param scope - an optional scope object for which the callback is applied to (callback.apply(scope,args))
 * @return (int) - 1=logged in, 2=guest, 0=not logged in
 *  Also calls callback, with UD for backwards compatibility.
 */
vyew.checkLogin=function(callback,scope,options)
{
	scope=(!scope) ? this : scope;
   	var ud=this.getUD();
	if(typeof(callback)!="function") callback=new Function();
    if(ud.em && ud.em.length>2){
		callback.apply(scope,[ud]);
		if(ud.em.indexOf('@')>0) return 1;
		return 2;
	}else{	
		callback.apply(scope,[false]);
		return 0;
	}
}
vyew.getUserInfo=vyew.getUserEmail=vyew.checkLogin;


/**
 * Validates an email address
 * @param em - the email address
 * @return boolean
 */
vyew.isEmailAddress=function(em)
{
    if (typeof em == "undefined") return false;
    if (typeof em == "object") em = em[0];
    em=''+em;
	if(em.match(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9_.-]+\.[a-zA-Z0-9]+$/)) return true;
    return false;
}


/**
 * Adds variables from sourceObj to targObj (not sure if cloned or not? todo: check it)
 * @param targObj 
 * @param sourceObj
 */
vyew.updateObj=function(targObj, sourceObj)
{
	if(typeof targObj != "object" || typeof sourceObj != "object") return;
	for(var v in sourceObj){
		targObj[v]=sourceObj[v];
	}
}





/**
 * ------------------------------------------------------------------
 * 	MISCELLANEOUS 
 * ------------------------------------------------------------------
 */


function getFirebugConsole()
{
	try{
	//if top frame, use that console
	if(top!=window) var win=top;
	else win=this.window;
	if(typeof win.console == "undefined"){ 
		if(!win.loadFirebugConsole) return false;
		else win.loadFirebugConsole();
	}
	if(typeof win.console != "undefined" && win.console.debug) return win.console;
	return false;
	}catch(e){ return false; }
}

function dbg()
{
	var console=getFirebugConsole();
	if (!console) return;
   	var out="";
   	try{for(var i=0;i<arguments.length;i++){ out+=arguments[i]+", "; }
   	out=out.substr(0,out.length-2);
 	console.debug(out);
	}catch(e){}
}
error_log=dbg

function dbd(x,txt)
{
	var console=getFirebugConsole();
	if(!console) return;
	try{
	if(txt) console.debug('---------------- '+txt);
	else console.debug('----------------');
    console.dir(x);
	}catch(e){}
}

//alert
function ale()
{
	var out="";
	for(var i=0;i<arguments.length;i++){ out+=arguments[i]+", "; }
	out=out.substr(0,out.length-2);
	alert(out);
}

/**
 * Searches through an object array for specified key/value within an object. 
 * Usage: a=[{id:1,name'bob'},{id:2,name:'joe'}]; 
 *        a.findObj('name','joe') //returns object:{id:2,name:'joe'}
 *        a.findObj('name','joe',true) //returns 1
 * @param key - String: the text of the variable name to search through
 * @param value - the value you are searching for
 * @param returnIndex - Bool: if true, return index, else return the object itself
 * @return: The found object, or its index
 */
Array.prototype.findObj = function(key, value, returnIndex ){
  for(var i in this){
     if (this[i][key] == value){ 
		if(returnIndex==true) return i
		else return this[i]
	 }
  }
  return false;
}

/** Starts preloading flex framework when page is done loading */
vyew.preloadFlex = function()
{
	try{
	$(window).load(function(){
		var vers=vyew.getVers();
		if(vers.match(/^v3/)) return;		//dont preload if v3.xx
		var swf="/"+vers+"/content/FlexPreload.swf?base=/"+vers+"/content/";
		var html="<div id='flexpreload' style='visibility:hidden;'>"
				+'<object width="1" height="1">'
				+'<param name="movie" value="'+swf+'">'
				+'<embed src="'+swf+'" width="1" height="1">'
				+'</embed></object></div>'
		$('body').append(html);
		//swfobject.embedSWF(swf, "flexpreload", 1, 1, "10.0");
	});
	}catch(e){}
}


/**
 * 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 sidp=getCookie('sidp');
	var lID=getCookie("lID");
	var kli=getCookie("keepLoggedIn");
	clearCookie("sid"); clearCookie("lID"); clearCookie("keepLoggedIn");
	clearCookie("sidp");
	setCookie("sid",sid);
	setCookie("sidp",sidp);
	if(lID && kli) setCookie("lID", lID, "forever");
	if(kli) setCookie("keepLoggedIn", kli, "forever");
}


if(Array.prototype.getUnique==null){
Array.prototype.getUnique=function()
{
	var newArray=new Array();
	label:for(var i=0; i<this.length;i++ )
	{  
		for(var j=0; j<newArray.length;j++ )
		{
			if(newArray[j]==this[i]) 
				continue label;
		}
		newArray[newArray.length] = this[i];
	}
	return newArray;
}
}

/**
 * Given a url: http://vyew.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") = "vyew.com"
 *      urlSegment("base") = "http://vyew.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;
    var loc=win.location.href.match(/\/\/(.*)/)[1];
    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 "";
}


/**
 * Returns specified segment after the hash (#) in url
 * A segment is text between "/" slashes
 * Examples with url : vyew.com/room#/abc/def/ghi
 *      hashUrlSegment(0) : "abc"  (leading slashes are removed)
 *      hashUrlSegment(1) : "def"
 *      hashUrlSegment() :
 * @param segNum - segment number
 * @return mixed - the segment specified or false
 */
function hashUrlSegment(segNum,win)
{
    if(!segNum) segNum=0;
    if(!win)win=this;
    var loc=this.location.href;
    pl=loc.indexOf("#");
    if(pl==-1) return false;
    if(!pl) return false;
    loc=loc.substr(pl+1)
    segs=loc.split("/");
    if(!segs[0]) segs.shift()
    return segs[segNum];
}

/**
 * Safely retrieve a property deep in an object of objects/arrays
 * such as x.y.z. After research the only safe way to check would be
 * if(x && x.y && x.y.z) return x.y.z
 * @param obj OBJECT - the base object from wihch to retrieve the property out of
 * @param path_string STRING - a string of dot notation of the property relative to
 *		 obj. In above example, get x.y.z: getprop(x, 'y.z')
 * @return MIXED - value of obj.eval(path_string), OR FALSE
 */
function getprop(obj, path_string) 
{
    var arr = path_string.split('.'),
    	val = obj || window;
 
    for (var i = 0; i < arr.length; i++) {
        val = val[arr[i]];
        if ( typeof val == 'undefined' ) return false;
		if ( i==arr.length-1 ) return val
    }
    return false;
}

/**
 * Same as getprop, except only returns TRUE or FALSE, not the value
 */
function isset(obj, path_string) 
{
	return (( getprop(obj, path_string) === false ) ? false : true)
}


function empty(v){
  if(typeof v == "undefined" || v==null || v==undefined || v=="") return true;
  else return false;
}



/**
 * sprintf and vsprintf for jQuery
 * somewhat based on http://jan.moesen.nu/code/javascript/sprintf-and-printf-in-javascript/
 * 
 * Copyright (c) 2008 Sabin Iacob (m0n5t3r) <iacobs@m0n5t3r.info>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details. 
 *
 * @license http://www.gnu.org/licenses/gpl.html 
 * @project jquery.sprintf
 */
(function($){
	var formats = {
		'b': function(val) {return parseInt(val, 10).toString(2);},
		'c': function(val) {return String.fromCharCode(parseInt(val, 10));},
		'd': function(val) {return parseInt(val, 10);},
		'u': function(val) {return Math.abs(val);},
		'f': function(val, p) {
			p = parseInt(p, 10); 
			val = parseFloat(val);
			if(isNaN(p && val)) {
				return NaN;
			}
			return p && val.toFixed(p) || val;
		},
		'o': function(val) {return parseInt(val, 10).toString(8);},
		's': function(val) {return val;},
		'x': function(val) {return ('' + parseInt(val, 10).toString(16)).toLowerCase();},
		'X': function(val) {return ('' + parseInt(val, 10).toString(16)).toUpperCase();}
	};

	var re = /%(?:(\d+)?(?:\.(\d+))?|\(([^)]+)\))([%bcdufosxX])/g;

	var dispatch = function(data){
		if(data.length == 1 && typeof data[0] == 'object') { //python-style printf
			data = data[0];
			return function(match, w, p, lbl, fmt, off, str) {
				return formats[fmt](data[lbl]);
			};
		} else { // regular, somewhat incomplete, printf
			var idx = 0; 
			return function(match, w, p, lbl, fmt, off, str) {
				if(fmt == '%') {
					return '%';
				}
				return formats[fmt](data[idx++], p);
			};
		}
	};

	$.extend({
		sprintf: function(format) {
			var argv = Array.apply(null, arguments).slice(1);
			return format.replace(re, dispatch(argv));
		},
		vsprintf: function(format, data) {
			return format.replace(re, dispatch(data));
		}
	});
})(jQuery);

