/**************************************************************
 * Created on January 2, 2010
 *
 *  Blabbers Communications Confidential
 *
 *  Source Materials.
 *
 *
 *  (C) Copyright Blabbers Communications Ltd. 2010
 *
 *  The source code for this program is not published or otherwise
 *  divested of its trade secrets, irrespective of what has been
 *  deposited with the U.S. Copyright Office.
 *
 *  Author: Blabbers Communications Ltd.
 **************************************************************/

var isBSessoin=null;
var addToUrl="";
var lastId=null;
var lastIdx=0;
var featuredOrLiveUgcArray= new Array();

var sessionId="";
var userId="";
var uname="";
var fbSessionId="";
var state = "";

var MAX_BLABS=4;
var MAX_MESSAGE_LENGTH = 80;

/// Live UGC management
var isShowLiveUGC = true;

var TIME_TO_REFRESH  = 30*1000;
var liveUGCTimer = null;

var lastAffId = "";

//-----------------------------------------
// BODY
//-----------------------------------------

  $(document).ready(function(){
	
	$("#featured_blabs").click(function () { 
		
		// $(this).find("img").attr({src: "images/popularBlabs_enabled.jpg"});
		// $("#live_blabs").find("img").attr({src: "images/liveblabs_disabled.jpg"});
		$(this).addClass("selected");
		$("#live_blabs").removeClass("selected");
		
		
		$("#liveText").css({"display":"none"});
		$("#popularText").css({"display":""});
		$("#nextLive").css({"display":"none"});
		$("#nextFeatured").css({"display":"none"});
		$("#tabsThingy").css({"left":"245px"});
		
		$("#blabs").html("");
		
		$("#ugc_loading").css({"display":""});
		
		
		
		getFeatueredUGCList();
		 
	});
	
	$("#nextFeatured").click(function () { 
				
		$("#nextFeatured_loading").css({"display":""});
		$("#nextFeatured").css({"display":"none"});
		
		getFeatueredUGCList();
		 
	});
	
	
	
	$("#live_blabs").click(function () { 
		// need to check if enabled already.
		// if yes, do nothing... otherwise, switch view
		
		// $(this).find("img").attr({src: "images/liveblabs_enabled.jpg"});
		// $("#featured_blabs").find("img").attr({src: "images/popularBlabs_disabled.jpg"});
		$(this).addClass("selected");
		$("#featured_blabs").removeClass("selected");
		
		$("#nextFeatured").css({"display":"none"});
		$("#nextFeatured_loading").css({"display":"none"});
		$("#popularText").css({"display":"none"});
		$("#nextLive").css({"display":""});
		$("#liveText").css({"display":""});
		$("#tabsThingy").css({"left":"85px"});

		$("#blabs").html("");
		$("#ugc_loading").css({"display":""});
		
		getLiveUGCList();
		 
	});
	
	$(".whistle_see").click(function () {
		onHeaderClick("whistle_see");
	});
	
	$(".surprise_see").click(function () {
		onHeaderClick("surprise_see");
	});
	
	$(".doodle_see").click(function () {
		onHeaderClick("doodle_see");
	});
	
	$(".contact").click(function () {
		onHeaderClick("contact");
	});
	
	$(".faq").click(function () { 
		onHeaderClick("faq");			
	});
	
	$(".terms").click(function () { 
		onHeaderClick("terms");			
	});
	
	$(".twt_profile").click(function () { 
		onHeaderClick("twt_profile");						
		
	});
	
	$(".fb_profile").click(function () { 
		onHeaderClick("fb_profile");						
		
	});
	
	$(".sitemap").click(function () { 
		onHeaderClick("sitemap");						
		
	});
	
	
});


//------------------------------------------
//------------------------------------------

function bbrs_log(txt){
	if(showDebugLog){
		alert(txt);
	}
}

function getState(){
	return state;
}

function setState(value){
	state=value;
}

function getSessionId(){	
	return sessionId;
}

function setSessionId(id){
	sessionId=id;
}
function getFbSessionId(){	
	return fbSessionId;
}

function setFbSessionId(id){
	fbSessionId=id;
}

function getUserId(){
	return userId;
}

function setUserId(id){
	userId=id;
}

function setUname(name){
	uname=name;
}
function getUname(){
	return uname;
}

//////////////////////////////////////////////////////////////////
/*
*    Server API AJAX Layer
*/
//////////////////////////////////////////////////////////////////

function getServerUrl(apiName) {
	
    // default API
    var url = serverURL + (useTestServer? "Test":"") + "ServiceOperation;jsessionid="+ getSessionId();
        
    if (apiName == 'ObjectAPI'){
        url = serverURL + (useTestServer?"Test":"") + "ObjectFinder;jsessionid="+ getSessionId()+"?";

    } else if (apiName == 'GalleryAPI'){
        url = serverURL + "Gallery;jsessionid="+ getSessionId();
    }
    var x= window.location.host.toLowerCase();
    if (x.indexOf("www")==-1) {
	url=url.replace("www.", "");
     }

	
    var y= window.location.protocol.toLowerCase();
    if (y.indexOf("https")>-1) {
	url=url.replace("http://", "https://");
     }
	
    return url;
}


/*
* getUserDetails API
*/
function getUserDetails(){

	var xmlData = '<BlabbersRequest xmlns="http://www.blabbers.com/commandfw">'+
	  		'<GetFriendDetailsRequest>'+
	    			'<sessionId>'+getSessionId()+'</sessionId>'+
				'<blabbersId>'+getUserId()+'</blabbersId>'+
				'<blabbersFriendId>'+getUserId()+'</blabbersFriendId>'+
	    			'<addStatistics>true</addStatistics>'+
	  		'</GetFriendDetailsRequest>'+
		       '</BlabbersRequest>';
	bbrs_log(xmlData);

	return callRemoteAPI('getUserDetails', "xmlData="+encodeURIComponent(xmlData), false, null);

}

/*
* getUGC 
*/
function getUGC(application,max,offset){
  	var xmlData = '<BlabbersRequest xmlns="http://www.blabbers.com/commandfw">'+
		'<GetUGCRequest>'+
			'<sessionId>'+getSessionId()+'</sessionId>'+
			'<blabbersId>'+getUserId()+'</blabbersId>'+
			'<max>'+max+'</max>'+
			'<offset>'+offset+'</offset>'+
            		'<application>'+application+'</application>'+
			'</GetUGCRequest>'+
		'</BlabbersRequest>';

	bbrs_log(xmlData);

	return callRemoteAPI('getUGC', "xmlData="+encodeURIComponent(xmlData), true, 'handleUGCCallback');
}

/*
* getFeatueredUGC
*/
function getFeatueredUGC(isLive,start,max,offset){	
	if(start==null){
		lastId=null;
		lastIdx=0;
	}
	var xmlData = '<BlabbersRequest xmlns="http://www.blabbers.com/commandfw">'+
   					'<GetFeaturedUGCRequest>'+
   						'<sessionId>'+getSessionId()+'</sessionId>'+
   						'<blabbersId>'+getUserId()+'</blabbersId>'+
   						'<isLive>'+isLive+'</isLive>';
	if(start){
		xmlData+=		'<startTime>'+start+'</startTime>';
	}
	if(max){
		xmlData+=		'<max>'+max+'</max>';
	}
	if(offset){
		xmlData+=		'<offset>'+offset+'</offset>';
	}
	xmlData +=     '</GetFeaturedUGCRequest>'+
				  '</BlabbersRequest>';
	

	var callback='handleFeaturedUGCCallback';

	if (isLive){
		callback='handleLiveUGCCallback';
	}

	bbrs_log(xmlData);
	
	return callRemoteAPI('getFeatueredUGC', "xmlData="+encodeURIComponent(xmlData), true, callback);
}

///////////////////////////////////////////////////////////////
//// HTTP Call to Server
///////////////////////////////////////////////////////////////
function callRemoteAPI(apiName, params, isAsync, callback){
	var httpRequest = ajaxRequest(getServerUrl(apiName), apiName, params, isAsync, callback);

	if (isAsync == false){  
		xmlData = "<xml>"+httpRequest.responseText+"</xml>";
			checkResponseStatus(apiName, xmlData);

		bbrs_log("Response Received ["+apiName+"]", "info");
		

		return xmlData;
	} else {
		bbrs_log("Response Received ["+apiName+"."+callback+"]: Server OK. please wait...", "info");

		return "ok";

	}

}

/*
* get data of Object by Type (user|ugc) and objectID (userId|ugcId);
* Synchronous API -- return XML with object data
*/
function getObjectData(objectType, objectID,full){
	var theResult = callRemoteAPI('ObjectAPI', getObjectAPIQueryString(objectType, objectID,full), false, '');

	if ((objectType=='ugc')&&(theResult!=null)){
	//	return xmldecode(theResult);
	}

	return theResult;
}

function getObjectAPIQueryString(objectType, objectID,full){
	return "Blabbersid="+getUserId()+"&ObjectType="+encodeURIComponent(objectType)+"&ObjectId="+encodeURIComponent(objectID)+"&full="+encodeURIComponent(full);
	//return "ObjectType="+encodeURIComponent(objectType)+"&ObjectId="+encodeURIComponent(objectID);
}

//---------------------------------------------------------------
// AJAX / Callbacks / Cross Domain
//---------------------------------------------------------------

function ajaxRequest(url, apiName, params, isAsync, callback) {

	bbrs_log("calling ["+apiName+"()]- AsyncMode="+isAsync+" CallbackMovie="+callback, "info");
	var req =null;
	try {
	   req = new ActiveXObject("Microsoft.XMLHTTP");    // Trying Internet Explorer 
	}
	catch(e)    // Failed 
	{
	  req = new XMLHttpRequest();    // Other browsers.
	}
	if (req) {
		if (isAsync == true) {
			req.onreadystatechange = function(){ // todo - to check is state is really ready
											handleResponseCallback(apiName, req, callback);
										}

			req.open("POST", url, true);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.send(params);
			

		} else { 
			req.open("POST", url, false);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.send(params);
			return req;
		}
	}
}

function handleResponseCallback(apiName, httpRequest, callback){

	//bbrs_log("state = "+httpRequest.readyState+ "data = "+httpRequest.responseText);
	
	if (httpRequest.readyState == 4){
		var xmlData = "<xml>"+httpRequest.responseText+"</xml>";

		bbrs_log("Async Response Received ["+apiName+"] TargetMovie="+callback+":", "info");
		bbrs_log(xmlData);
		

		handleResponseCallbackImpl(apiName, xmlData, callback);
	}

}


function handleResponseCallbackImpl(apiName, xmlData, callback){
	var status = checkResponseStatus(apiName, xmlData);
	// handle callback 
	if (callback != null) {
		switch (callback){
			case "auto_login":
				bbrs_log("auto_login callback, status = "+status);
				handleAutoLoginResponseCallback(status, xmlData);
				break;
			case "handleUGCCallback":
				handleUGCCallback(status, xmlData);
				break;
			case "handleFeaturedUGCCallback":
				  handleFeaturedUGCCallback(status, xmlData);
				  break;
			case "handleLiveUGCCallback":
				  handleLiveUGCCallback(status, xmlData);
				  break;
			default:
				bbrs_log("Flash Movie callback ["+callback+"]");
				getFlashMovie(callback).onCommand(apiName, xmlData);

		}
		
	} else {
		bbrs_log("todo - handleResponseCallbackImpl");
	}

}

function checkResponseStatus(apiName, responseXML){
	var status = $(responseXML).find('status').text();

	return status;
}

/////////////////////////////////////////////////////////////////////
/// callbacks
////////////////////////////////////////////////////////////////////

function handleUGCCallback(status, xmlData){
	//alert("handleUGCCallback");
}

function handleLiveUGCCallback(status, xmlData){
	//alert("status= "+status+"; data="+xmlData);
	
	if (isShowLiveUGC) {
		$("#ugc_loading").css({"display":"none"});
		$(".nextFeatured").css({"display":"none"});
		
		drawUGC(status, xmlData, true);
		
		 liveUGCTimer = setTimeout("getLiveUGCList()", TIME_TO_REFRESH);
		
	}
	
	
	
	
}

function handleFeaturedUGCCallback(status, xmlData){
	//alert("status= "+status+"; data="+xmlData);
	
	if (!isShowLiveUGC) {
		$("#ugc_loading").css({"display":"none"});
		$("#nextFeatured").css({"display":""});
		$("#nextFeatured_loading").css({"display":"none"});
		
		drawUGC(status, xmlData, false);
	}
	
}

function drawUGC(status, xmlData, isLive){

	var i=0;
	var j=0;
	var height = 40;
	var str='' ;	
	$(xmlData).find("UGCs").each(function(){
		var ugc;
		var tempUgc=null;
		$(this).find("UGC").each(function(){
		if (i++ == 2) return;
			
			var currentUGC = $(this);
			ugc = parseUGC(currentUGC);
			lastId=ugc[0];	
			
			var newUGC = createUgcUIelement(ugc);
			tempUgc=featuredOrLiveUgcArray[lastIdx];
			if(tempUgc){
				removeUGCFromHtml(tempUgc);
			} 
			if (isLive) {
				$("#blabs").prepend(newUGC);
			} else {
				$("#blabs").append(newUGC);
			}
			
			newUGC.css({"display":""});
			
			featuredOrLiveUgcArray[lastIdx]=ugc;
			lastIdx++;
			
			if(lastIdx==MAX_BLABS){
				lastIdx=0;
			}	
		});
	});
}


function parseUGC(currentUGC){
	var ugc;
	ugc = new Array();
	ugc[0] = currentUGC.find('ugcId').text();
	ugc[1] = currentUGC.find('type:first').text();
	ugc[2] = parseFromDetails(currentUGC.find('from'));
	ugc[3] = currentUGC.find('isPublic').text();
	ugc[4] = currentUGC.find('text').text();
	ugc[5] = decodeURIComponent(currentUGC.find('leadUrl').text());
	ugc[6] = parseFromDetails(currentUGC.find('owner'));
	ugc[7] = currentUGC.find('context').text();
	ugc[8] = currentUGC.find('ugcParentId').text();
	ugc[9] = currentUGC.find('likes').text();
	ugc[10] = currentUGC.find('dislikes').text();
	ugc[11] = currentUGC.find('myrate').text();
	ugc[12] = currentUGC.find('wasRead').text();
	ugc[13] = currentUGC.find('subtype').text();
	ugc[14] = currentUGC.find('icon').text();
	ugc[15] = currentUGC.find('scope').text();
	ugc[16] = currentUGC.find('timestamp').text();
	ugc[17] = currentUGC.find('screenLocation').text();
	ugc[18] = currentUGC.find('affId').text();

	
	return ugc;
}

function handleObjectFinderCallback(xmlData){

	$(xmlData).find("ugc").each(function(){
		var currentUGC = $(this);

		ugc = parseUGC(currentUGC);
		showGraffiti(ugc);		

	});
	
	
}

function parseFromDetails(from){
	var parsedFrom = new Array();
		parsedFrom[0] = $(from).find('type').text();
		parsedFrom[1] = $(from).find('blabbersId').text();
		parsedFrom[2] = $(from).find('userName').text();
		parsedFrom[3] = $(from).find('pictureurl').text();
		
	return parsedFrom;
}

///////////////////////////////////////////////
//////////// UI
///////////////////////////////////////////////

function addWidget(divID, isDraggable,isUnique, innerContent, w, h, top, left){
   
    if (isUnique == true){ // remove is already in DOM
        $("#"+divID).remove();
    }
	
	
	var blabbersDefaultStyle ='position:fixed;z-index:2147483640; background: none; margin:0px; overflow: hidden;border:0px; padding:0px;';
	
	var theDiv = $("<div id='"+divID+"' style='"+blabbersDefaultStyle+"'>"+innerContent+"</div>");
	
	if (top){
		$(theDiv).css("top",top);
	} 
	
	if (left){
		$(theDiv).css("left",left);
	}

	if (w){
		$(theDiv).css("width",w);
	} 
	
	if (h){
		
		$(theDiv).css("height",h);
	}
	
	$("body:first").append(theDiv);
	
	
	if (isDraggable == true){
		$(theDiv).draggable();
	}
	
	return theDiv;


}


//////////////////////////////////////////////////////////////////////////////
//// flash helpers
/////////////////////////////////////////////////////////////////////////////
// MAIN functions for callback to Flash movies.
function getFlashMovie(movieName) {
    if('\v'=='v'){
        //code for IE
          return window[movieName];
      }else{
          //Other browser
	  return window.document[movieName];
    }       
}


function showDownloader(){	
	var top = ''+(getPageHeight()/5)+'px';
	var left = ''+(getPageWidth()/3)+'px';

	$("#bbrs_downloader").css({"top": top, "left": left});
	$("#bbrs_downloader").css({"display":""});
	
	//$("#bbrs_downloader").draggable();
}

function onDownloaderClick(value){
	bbrs_log(value);
	
	sendGAT("download");
	var dir = "";
	var eAffId = "blabbers";
	
	if ((lastAffId!="")&&(lastAffId!="blabbers")&&(lastAffId!="null")) {
		try{
			if(lastAffId=="CT7219310") lastAffId="CT2719310";
		}catch(err){}

		//dir = lastAffId+"/";
		dir = lastAffId+"/"+lastAffId+"-";
		eAffId = lastAffId;
	}
	//alert("lastAffId = " + lastAffId);
	
	switch(value){
		case "download_ie":
			//alert("download ie");
			sendGATEvent(eAffId, "download", "ie", 0);
			if(eAffId.indexOf("CT")==0){
				window.location="http://"+eAffId+".ourtoolbar.com/IE";
				return;
			}
			//window.location = "download/" + dir + "blabbers_ie.exe";
			window.location = "download/" + dir + "blabbers.exe";
			break;
		case "download_ff":
			sendGATEvent(eAffId, "download", "ff", 0);
			
			if(eAffId.indexOf("CT")==0){
				window.location="http://"+eAffId+".ourtoolbar.com/XPI/";
				return;
			}

			if(navigator.platform == "Mac" ) window.location = "download/"+dir+"blabbers.xpi";
			else if((dir!="")&&(eAffId.indexOf("CT")!=0)) window.location = "download/" + dir + "blabbers.exe";
			//else if(dir!="") window.location = "download/" + dir + "blabbers.exe";
			else window.location = "download/" + dir + "blabbers.xpi";
			//else window.location = "download/blabbers_ff.exe";
			
			break;
		case "download_chrome":
			sendGATEvent(eAffId, "download", "chrome", 0);
			if(navigator.platform == "Mac" ) window.location = "download/"+dir+"blabbers.crx";
			else window.location = "download/" + dir + "blabbers.crx";
			//else window.location = "download/blabbers_ff.exe";
			
			break;
		case "downloader_privacy":
			onHeaderClick("terms");
			break;
		default:
			window.location = "download/" + dir + "blabbers.exe";
	}
	
	// whatever option - need to close the downloader after execution...
	$("#bbrs_downloader").css({"display":"none"});
	
}

function showLogin(){	
	
	var top = ''+(getPageHeight()/4)+'px';
	var left = ''+(getPageWidth()/3)+'px';

	$("#bbrs_login").css({"top": top, "left": left});
	$("#bbrs_login").css({"display":""});
	
	//$("#bbrs_downloader").draggable();
}

window.onLoginCommand = function (command, params){
	bbrs_log(command);
	
	switch(command){
		case "showPrivacyTerms":
			onHeaderClick("terms");
			break;
		case "executeDefaultLoginFlow":
			doLogin();
			break;
		default:
	}
	
	// whatever option - need to close the downloader after execution...
	$("#bbrs_login").css({"display":"none"});
	
}

function showTryMe(){
	var top = '0px';
	var left = '0px';
	
	var _flashoverlay_script=document.createElement('script');
	_flashoverlay_script.type='text/javascript';
	_flashoverlay_script.src='http://www.blabbers.com/app/bookmark/bookmarklet/bbrsOverlay.php?m=lite&wid=5&affId=blabbers&hideIframes=true&configData=isPreviewMode%3Dtrue%26t%3DugcId%26ugcId%3D2%26portal%3D1%26showTryMe%3D1';
	document.getElementsByTagName('head')[0].appendChild(_flashoverlay_script);
}

function showBlabox(viewUserId){
	//var top = '50px';
	//var left = ''+(getPageWidth()/4.5)+'px';
	
	var blaboxSWF = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="100%" height="100%" id="blabox" align="middle"><param name="allowScriptAccess" value="sameDomain" /><param name="allowFullScreen" value="false" /><param name="wmode" value="transparent" /><param name="FlashVars" value="wid=Blabox'+swfBuildVer+'&portal=1&'+getManagerConfigData()+'" /><param name="movie" value="../widgets/LitePortalManager'+swfBuildVer+'.swf" /><param name="quality" value="high" />	<embed src="../widgets/LitePortalManager'+swfBuildVer+'.swf" quality="high" wmode="transparent" width="100%" height="100%" name="blabox" flashvars="wid=Blabox'+swfBuildVer+'&portal=1&'+getManagerConfigData()+'" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" /></object>';
	
	//addWidget("bbrs_blabox", false, true, blaboxSWF, null, null, top, left);
	addWidget("bbrs_blabox", false, true, blaboxSWF, getPageWidth() + "px", getPageHeight() + "px", '0px', '0px');	

}

window.onBlaboxCommand = function (command, params){
	
	switch (command) {
		case "ugcView":
			showPreview(params[0], params[1], params[2]); // TDOD !!!!
			break;
			
	}
	
	// whatever option - need to close the downloader after execution...
	$("#bbrs_blabox").remove();
	
}

window.onViewrCommand = function (command, params){	
	switch (command){
		case "showLogin":
			showLogin();
			break;
			
		case "showDownloader":
			lastAffId = params;
			showDownloader();
			break;
		case "directDownload":
			lastAffId = params;
			directDownload();
			break;
		case "goPageBack":
			window.history.back();
			break;
		default:
			$("#bbrs_viewer_container").css({"display":"none"});
			$("#bbrsLiteMgr_container").css({"display":"none"});
			try{
				//if on preview
				closePreview();
			}catch(err){}
			//window.close();
	}
	

}

window.directDownload = function(isPortal) {
	var btype = getBrowser();
	switch(btype){
		case(0):
			onDownloaderClick("download_ie");
			break;
		case(1):
			onDownloaderClick("download_ff");
			break;
		case(2):
			onDownloaderClick("download_chrome");
			break;
		default:
			if (isPortal){
				showDownloader();
			} else {
				window.top.location=X_URL;
			}
			
			break;
	}
}

window.onContactsCommand = function (command, params){
	window.location = params;
}

function bbrs_navigate (url, context){
	var urlOld = window.top.location.href;
	if(urlOld==url){
		urlOld=null;
		window.location.reload(false);
	}else{
		urlOld=null;
		window.top.location=url;
	}
}
		
window.bbrsOnCommand = function (command, params) {
	switch (command) {
		case "redirect":
						var url=null;
						if(params=="portal") url=serverURL() + "portal/main.jsp";
						else if (params=="privacy") url=serverURL() + "portal/terms.jsp";
						else if (params=="help") url=serverURL() + "portal/faq.jsp";
						else if (params=="invite") url=serverURL() + "portal/invite.jsp";
						else if (params.substr(0, 8)=="language") url = serverURL() + "portal/blabMultilingual-" + params.substr(8) + ".jsp";
						else if (params=="search") url="http://www.blabbers.com/search.jsp";
						else if (params=="facebook") url="http://www.facebook.com";
						else if (params=="refresh") {
							url=window.top.location;					
						} else url=params;


						if(url) bbrs_navigate (url,"");
			break;
		case "resizeManager":
			$("#bbrs_viewer_container").css("width",params[0]);
			$("#bbrs_viewer_container").css("height",params[1]);
			
			//alert("expanding blabbers viewer= "+params[0]+";"+params[1]);
			
			break;
		case "sendGAT":
			sendGAT(params);
			break;
		case "sendGATEvent":
		        var category=params[0];
		        var action=params[1];
		        var optional_label=null;
		        var optional_value = null;
		        if(params.length==4){
		        	optional_label=params[2];
		        	optional_value=0;
		        }
			sendGATEvent(category, action, optional_label, optional_value);
			break;
		case "setParam":
			break;
		case "getPageHeight":
			  return getPageHeight();
		
		case "getParam":
			return "null";
	}
	
}

function showPreview(ugcId, url, screenLocation){
	var b = "1";
	//alert("show preview");
	if(g_api){
		//alert("gapi");
	//	g_api.redirectAndViewUGC(ugcId, url, "newtab");
		//TODO call flash in load manager
		
		b = "0";
		
	}else{
		//alert("not gapi");
		b = "1";
		
	}
	
	if (!screenLocation) screenLocation = "";
    if (!url) url="";
	var winUrl='preview.jsp?ugcId='+ugcId+((url!='')?'&url='+encodeURIComponent(url):'')+((screenLocation!='')?'&sl='+screenLocation:'')+'&b='+b;
	//alert(winUrl);
	window.open(winUrl,'newtab');
	
}


function onHeaderClick(name){

	bbrs_log(name);
	switch(name){
		case "btn_logo":
		case "btn_home":
			window.location = "main.jsp";
			break;
		case "btn_invite":
			window.location = "invite.jsp?fbSid="+getFbSessionId();
			break;
		case "btn_download":
			showDownloader();
			break;
		case "btn_aboutUs":
			window.location = "about.jsp";
			break;
		case "btn_myprofile":
			showBlabox();
			break;
		case "btn_login":
			//showLogin();
			doLogin();
			break;
		case "btn_logout":
			//window.location = "?logout=1";
			doLogout();
			break;
		case "terms":
			window.location = "terms.jsp";
			break;
		case "twt_profile":
			window.location = "http://twitter.com/BlabbersWorld";
			break;
		case "fb_profile":
			window.location = "http://www.facebook.com/apps/application.php?id=186982569263";
			break;
		case "help":
			window.location = "help.jsp";
			break;
		case "faq":
			window.location = "faq.jsp";
			break;
		case "contact":
			window.location = "contact.jsp";
			break;
		case "doodle_see":
			window.location = "widgets.jsp?w=1";
			break;
		case "whistle_see":
			window.location = "widgets.jsp?w=2";
			break;
		case "surprise_see":
			window.location = "widgets.jsp?w=3";
			break;
		case "btn_bloger":
			window.location = "bloger.jsp";
			break;
		case "btn_publisher":
			window.location = "publisher.jsp";
			break;
	}
}

//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////

function htmlspecialchars(string, newline) {
string = string.toString();
if (newline) {
string = string.replace(/\n/g, '');
} else {
string = string.replace(/\n/g, '<br/>');
}
string = string.replace(/&/g, '&');
string = string.replace(/%/g, '%25');
string = string.replace(/</g, '&lt;');
string = string.replace(/>/g, '>');
return string;
}

function xmlencode(string) {
	return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;')
		.replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
}

function xmldecode(string) {
	return string.replace(/&/g,'&').replace(/</g,'<')
		.replace(/>/g,'>').replace(/'/g,'\'').replace(/"/g,'\"');
}

/////////////////////////////////////////////////
function getUniqueID(){
	var expdate = new Date ();
	return expdate.getTime();
}

function getPageWidth(){
	if(window.innerWidth){
        width=window.innerWidth - 16;
    }else{
       width=document.documentElement.clientWidth;
    }
	
	return width;
}

function getPageHeight(){
	if(window.innerHeight){
        height=window.innerHeight;
    }else{
       height=document.documentElement.clientHeight;
    }
	
	return height;

}


//----------------------------------------------------------
// Blabox APIs
// ---------------------------------------------------------
function getBlaboxAll(){
	if(boxType!=1){
		offset=0;
		boxType=1;
	}
	nextContent();
}
function getBlaboxMe(){
	if(boxType!=2){
		offset=0;
		boxType=2;
	}
	nextContent();
}
function getBlaboxFriends(){
	if(boxType!=3){
		offset=0;
		boxType=3;
	}
	nextContent();
}

function nextContent(){
	var application='BlaboxAll';
	if(boxType==1){
		application='BlaboxAll';
	}else if(boxType==2){
		application='BlaboxMyBlab';
	}else if(boxType==3){
		application='BlabboxMyFirends';
	}
	getUGC(application,MAX,offset);
	offset=offset+MAX;
}

function getFeatueredUGCList(){
	isShowLiveUGC = false;
	
	if (liveUGCTimer!=null){
		try {
			clearTimeout(liveUGCTimer);
		} catch (err){
			//alert("error clearning Live UGC timer - "+err.description);
		}
	}
	
	
	if(startL){				
		startL=null;
		offsetFeatured=0;
		featuredOrLiveUgcArray= new Array();
	}
	getFeatueredUGC(false,null,MAX_BLABS,offsetFeatured);
	startF=new Date().getTime();
	offsetFeatured=offsetFeatured+MAX_BLABS;
}

function getLiveUGCList(){
	isShowLiveUGC = true;
	
	if (liveUGCTimer!=null){
		try {
			clearTimeout(liveUGCTimer)		;
		} catch (err){
			//alert("[getLiveUGCList] error clearning Live UGC timer - "+err.description);
		}
	}
	
	if(startF){
		startF=null;
		offsetFeatured=0;
		featuredOrLiveUgcArray= new Array();
	}
	if(startL==null){
		getFeatueredUGC(true, null, MAX_BLABS);
		startL=new Date().getTime();
	}else{
		getFeatueredUGC(true,startF, MAX_BLABS);
		startL=new Date().getTime();
	}
	
	

}

function alertSize() {
  var myWidth = 0, myHeight = 0;
  
  alert ("window.height=" + window.innerHeight);
  alert( "document.documentElement.height=" + document.documentElement.clientHeight);
  alert("document.documentElement.scrollHeight ="+document.documentElement.scrollHeight );
  
  alert("$(document).height()="+$(document).height());
  alert("$(document).height()="+$(window).height());
}

function getManagerConfigData(){
	var width=0;
	var height=0;	
	
	if(document.documentElement.clientWidth){
       width=document.documentElement.clientWidth;
	   height=document.documentElement.clientHeight;
    }else{
		width=window.innerWidth;
		height=window.innerHeight;
    }
	
	var viewerByAffiliate = swfBuildVer;
		
		if (lastAffId.indexOf("CT")==0) {
			viewerByAffiliate += "Conduit";
		} 
	
						
	var settings= 	"hidden=false" +
                    "&pathLogin=" + getWidgetURL("login.swf") +
					"&pathWhistle=" + getWidgetURL("whistle"+swfBuildVer+".swf") +
                    "&pathAmbush=" + getWidgetURL("Surprise"+swfBuildVer+".swf") +
                    "&pathGrafiti=" + getWidgetURL("blabEditor"+swfBuildVer+".swf") +
                    "&pathBlabox=" + getWidgetURL("Blabox"+swfBuildVer+".swf") +
					"&pathViewer="+ getWidgetURL("Viewer"+viewerByAffiliate+".swf") +
					"&pathSettings="+ getWidgetURL("settings"+swfBuildVer+".swf") +
					"&pathWidgets="+ widgetsLocationURL +
					"&serverURL="+ serverURL +
					"&settingsMode=minimal"+
					"&pathBlabViewer="+ getWidgetURL("blabViewer"+swfBuildVer+".swf") +
					"&screenWidth="+ width+
					"&screenHeight="+height+
					"&viewedScreenHeight="+ height+
					"&firstRun=0"+
					"&browser="+getBrowser()+
					"&onCommand=bbrsOnCommand"+
					"&language="+getDefaultLanguage();
    return settings;
}

function getBrowser() {
	var browser = $.browser;
	if (browser.msie) return 0;
	else if (browser.mozilla) return 1;
	else if (browser.webkit) return 2;
	else if (browser.safari) return 3;
	else if (browser.opera) return 4;
	else return 0;
}

function getDefaultLanguage() {
	return "en";
	/*var userLang = (wit_getRootWindow().navigator.language) ? wit_getRootWindow().navigator.language : wit_getRootWindow().navigator.userLanguage; 
	
	if (userLang){
		var language = userLang.split("-")[0];
		if (language == "en" || language == "ru" || language == "he") return "en";
		else return "en";
	} else {
		return "en";
	}*/
}

function getWidgetURL(name){
	return widgetsLocationURL+name;
	
}

/*
function flHideMovie() {
	document.getElementById("divFlashMovie").style.display = 'none';
}
function flShowMovie() {
	
	document.getElementById("divFlashMovie").style.display = 'block';
}
*/
