var isUserTryToLogin=false;
///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// common SESSION object //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

window.SESSION = window.SESSION || {};

///////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// LOGGER ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
 
window.LOGGER = {     debug : false};

LOGGER.init = function(debugMode)
{
    this.debug = ( debugMode == "true" );
    if (this.debug)
        this.wnd = window.open("about:blank");
}

LOGGER.error = function(message, data)
{
    this.trace(message, data, "lightcoral");
}

LOGGER.info = function(message, data)
{
    this.trace(message, data, "lightgreen");
}

LOGGER.warn = function(message, data)
{
    this.trace(message, data, "yellow");
}

LOGGER.defined = function(name)
{
    this.println(name +" was defined", "aqua");
}

LOGGER.trace = function(message, data, color)
{
    var str = message + " data: " + UTILS.JSONobjectToString(data == null?"null":data);
    this.println(str, color);
}

LOGGER.println = function(str, color)     //private
{
    if (!this.debug)    return;

    str = str.replace(/</g, "{");
    str = str.replace(/>/g, "}");

    try
    {
        var dc = this.wnd.document;
        var span = dc.createElement("div");
        span.style.backgroundColor = color || "white";
        span.innerHTML = str + "<br/>";
        dc.body.appendChild(span);
    }
    catch(e) {
    }
}

LOGGER.init(SESSION.debug);
LOGGER.defined("LOGGER");

///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// UTILES /////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

window.UTILS = {};

/* 
* Returns type of object .
*/

UTILS.getType   = function(object)
{
    return String(typeof(object)).toLowerCase();
}

/* 
* It converts JSON object to string.
*/

UTILS.JSONobjectToString = function(object)
{
    return JSON.objectToString ( object );
}

/* 
* Returns minimum  value from given values.
*/

UTILS.min = function(a, b)
{
    return a < b? a:b;
}
/* 
* Returns maximum  value from given values.
*/

UTILS.max = function(a, b)
{
    return a > b? a:b;
}

/* 
* Returns a resulting pattern .
* Replaces given map in to specified pattern.
* Gives resulting source file after creating any event.
*/

UTILS.replace = function (pattern, map)
{
    for (var key in map)
    {
        var value = map[key];
        if (key.indexOf('~') == 0)
        {
            var regexp = key.substring(1, key.length).split("/");
            key = new RegExp(regexp[1], regexp[2]);
        }
        pattern = pattern.replace(key, value);
    }

    return pattern;
}

/* 
* Returns given string is empty or not  .
*/

UTILS.isEmpty = function (str)
{
    return (str == null || str.length == 0);
}

/* 
* Returns copy of given string .
*/

UTILS.setCopy = function (a)
{
    var c = {};
    for (var key in a) c[ key ] = a[ key ];
    return c;
}

/* 
* It creates left join to the given value with new value
* Returns   combination of given and exsting value in left join  format.
*/

UTILS.leftJoin = function (a, b)
{
    var c = this.setCopy(a);
    for (var key in b) c[key] = c[key] || b[key];
    return c;
}

/* 
* It creates right join to the given value with new value
* Returns   combination of given and exsting value in right jon format.
*/

UTILS.rightJoin = function (a, b)
{
    return this.leftJoin(b, a);
}

/* 
* Returns  a null value among given values.
*/

UTILS.notNULL = function (a, b)
{
    return a == null? b : a;
}

/* 
* Returns a new value for empty value.
* It first checks which value is empty, then it creats a defination for that value and asign others value to that one.
*/

UTILS.def = function(a,b)
{
    return UTILS.isEmpty(a) ? b : a;
}

UTILS.def2 = function(a,b)
{
    return UTILS.isEmpty(a) ? b : encodeURIComponent(a);
}

UTILS.compile = function(hash)
{
    var str = "";
    for (var key in hash)
    {
        if(key.indexOf("cmd") != -1) continue;
        str += (hash[key] == null) ? "" : ("&" + key + "=" + encodeURIComponent( hash[key] ));
    }
    return str;
}

UTILS.decompile = function(string)
{
    var hash = {};
    var pairs = string.split("&");
    for ( var key in pairs )
        if ( pairs[key] != "" )
        {
            var keyValue = pairs[key].split("=");
            hash[keyValue[0]] = decodeURIComponent(keyValue[1]);
        }
    return hash;
}

UTILS.contains = function(array, obj)
{
    for(var key in array)
        if (array[key] == obj)
            return true;
    return false;
}

UTILS.replaceAttribute = function(strBase, attrName, strNew)
{
    var index1 = strBase.indexOf(attrName);
    var index2 = strBase.indexOf("\"", index1+1);
    var index3 = strBase.indexOf("\"", index2+1);
    return strBase.substring(0, index2+1)+strNew+strBase.substr(index3,strBase.length);
}

UTILS.getShortFeed = function(longFeedName)
{
    if (longFeedName.indexOf("sharefun-email-") ==0)
        return longFeedName.substr(15);

    if (longFeedName.indexOf("sharefun-phone-") ==0)
        return longFeedName.substr(15);

    return longFeedName;
}

LOGGER.defined("UTILS");
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////// Validate URL /////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* 
* It validate the given url.
* Return a true or false value.
*/


function Validate(form) { 
    var v = new RegExp(); 
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"); 
    if (!v.test(form["URL"].value)) { 
        alert("You must supply a valid URL."); 
        return false; 
    } 
} 

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// SERVER //////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

window.SERVER = { listeners : {} };

SERVER.doNothingFunction = function() {};

/* 
* Returns a password in encoded format.
* All manipulation are done by "des" algorithm placed in des.js file.
*/

SERVER.getPasswordDigest = function(password)
{
	
    var keySHA = str_sha1("E7FA2A39D9054845A60C258E242AE0D09AD94A8A49F244a581D2FBE06B08F3576C88D3FB9A1745e4B831AA8A5A8590614A5BA27333A24789A1F18B015C6CB5FD").substr(0,8);
    
	var align = 8 - (password.length % 8);
	
	if((password.length % 8) != 0)
	for(i=0;i<align;i++)
		password=password+"\0";
	return encode64(des(keySHA, password, 1, 0));
}

/* 
* Returns a new XMLHTTP request according to given event.
*/

SERVER.createXMLTTTPRequest = function()
{
    if ( window.XMLHttpRequest )
        return new XMLHttpRequest();

    if ( window.ActiveXObject)
        try
        {
            return new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch( e )
        {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
}

/* 
* Returns a headers for given post event.
*/

SERVER.subscribe = function(post)
{
    var headers = {
        "Authorization": "WSSE profile=\"UsernameToken\"",
        "Content-Type" : (post? "application/javascript" : "application/x-www-form-urlencoded"),
        "X-WSSE":           STORAGE.getWsseHeader(),
		"umundo-timestamp": isodatetime(),
		"umundo-uid":"C5B47355E46D495EBE6AF35B073EEFEF"};
    return headers;
}

/* 
* It calls to specified handler class according to request status.
* There are 4 parameter for this method i.e. req,requestMessageHash, commandKey, callBackFunctionName.
* According to req.status value resulting handler get called. 
* callBackFunctionName is declared in Map of SERVER object . 
* commandKey is a method name defined in handler class.
*/


SERVER.getHandler = function( req, requestMessageHash, commandKey, callBackFunctionName )
{
    return function ()
    {
        var x4 = req.readyState;
        if ( x4 != 4 ) return;
		switch (req.status)
        {	
            case 200:
                SERVER.requestMessageHash = requestMessageHash;
                try
                {
					var retValue = JSON.getObjectFromString(req.responseText);
                    retValue.data = requestMessageHash;
					
                    SERVER[callBackFunctionName](commandKey, retValue);
                }
                catch (e)
                {
					STORAGE.clearWsseHeader();
					STORAGE.clearUserName();
					document.getElementById('errorMessage').style.display='block';
					document.getElementById('errorMessage').innerHTML="User authentication failed. Invalid username or password.<div align='right'><a href='javascript:hidebtn();' class='hide_btn'>Hide</a></div>";
                }
                break;
            case 403:
				SERVER.requestMessageHash = requestMessageHash;
                try
                {
					
                    var retValue = JSON.getObjectFromString(req.responseText);
					
                    retValue.data = requestMessageHash;
					
                    SERVER[callBackFunctionName](commandKey, retValue);
                }
                catch (e)
                {
                	STORAGE.clearWsseHeader();
					STORAGE.clearUserName();
					document.getElementById('errorMessage').style.display='block';
					
					//isUserLoggedin=STORAGE.getUserLoggedin()
					//alert("isUserLoggedin in 403=="+isUserLoggedin);
					if(isUserTryToLogin==true)
					document.getElementById('errorMessage').innerHTML="User authentication failed. Invalid username or password.<div align='right'><a href='javascript:hidebtn();' class='hide_btn'>Hide</a></div>";
					
					else
					document.getElementById('errorMessage').innerHTML="User authentication failed. Invalid username or password.<div align='right'><a href='javascript:hidebtn();' class='hide_btn'>Hide</a></div>";
					
                }
                break;
            case 401:
                SERVER.requestMessageHash = requestMessageHash;
                try
                {
					
                    var retValue = JSON.getObjectFromString(req.responseText);
                    retValue.data = requestMessageHash;
					
                    SERVER[callBackFunctionName](commandKey, retValue);
                }
                catch (e)
                {
                	document.getElementById('errorMessage').style.display='block';
					document.getElementById('errorMessage').innerHTML="You have to login to do this action.<div align='right';valign='top'; class='hide_btn';><a  href='javascript:hidebtn()'>Hide</a></div>";
					window.scrollTo(0,0);
                }
                break;
            default:
                SERVER.OnCriticalError(req.status);
        }
    }
}

/* 
* Its a very important and common method for every event.
* Returns request body for specified event. 
* It creates asynchronous AJAX call.
* It is a request method for every other methods.
*/

SERVER.sendMessageAuth = function(commandKey, message, post)
{
    //patch 03
	
    message.alias = message.login;
   
    var url = SESSION.http_rpc + message.cmd + "?";
    var body = "";
   
    if (post)
        body += UTILS.JSONobjectToString(message);
    else
        url += UTILS.compile(message);
	 
    var req = this.createXMLTTTPRequest();

    req.open(post ? 'POST' : 'GET', url, true);

    var headers = this.subscribe(post);
     for ( var param in headers )
        if ( headers[param] != null && headers[param] != "" )
        {
           
            req.setRequestHeader(param, headers[param]);
            }
	
	var umundo_signature = hex_hmac_sha1("E7FA2A39D9054845A60C258E242AE0D09AD94A8A49F244a581D2FBE06B08F3576C88D3FB9A1745e4B831AA8A5A8590614A5BA27333A24789A1F18B015C6CB5FD", 
		message.cmd + headers["umundo-timestamp"]);

	req.setRequestHeader("umundo-signature", umundo_signature);
	
    req.onreadystatechange = this.getHandler(req, message, commandKey, "OnMessageAuth");
	
    LOGGER.trace("sendMessageAuth", {"url":url},"lightblue");
    LOGGER.trace("sendMessageAuth", {"body":body},"lightblue");
   
    req.send(body);
	
}

/* 
* Its a very important and common method for every event which requires synchronous call.
* Returns request body for specified event. 
* It creates synchronous AJAX call.
*/

SERVER.sendMessageAuthSynch = function(commandKey, message, post,frompage)
{
    //patch 03
	
    message.alias = message.login;

    var url = SESSION.http_rpc + message.cmd + "?";
    var body = "";

    if (post)
        body += UTILS.JSONobjectToString(message);
    else
        url += UTILS.compile(message);
	 
    var req = this.createXMLTTTPRequest();
	
    req.open(post ? 'POST' : 'GET', url, false);

    var headers = this.subscribe(post);
     for ( var param in headers )
        if ( headers[param] != null && headers[param] != "" ){
           
            req.setRequestHeader(param, headers[param]);
            }
	
	var umundo_signature = hex_hmac_sha1("E7FA2A39D9054845A60C258E242AE0D09AD94A8A49F244a581D2FBE06B08F3576C88D3FB9A1745e4B831AA8A5A8590614A5BA27333A24789A1F18B015C6CB5FD", 
		message.cmd + headers["umundo-timestamp"]);

	req.setRequestHeader("umundo-signature", umundo_signature);
	
   // req.onreadystatechange = this.getHandler(req, message, commandKey, "OnMessageAuth");
	
    LOGGER.trace("sendMessageAuth", {"url":url},"lightblue");
    LOGGER.trace("sendMessageAuth", {"body":body},"lightblue");
   
    req.send(body);
	var retValue = JSON.getObjectFromString(req.responseText);
	   var error = retValue.error, result = retValue.result;
	//alert("retValue  error="+error+"\n result="+JSON.array(result));
	//alert("from page="+frompage);
	if(frompage=="fileformat")
	{
		if(result==null)
		{
			 isValidFileformat=false;
		}
		 else
		{
			 isValidFileformat=true;
		}
		SERVER.OnIsSupportedFormat(result,error);/* Call the callback method of file format checking*/
	}
	else if(frompage=="clipformat")
	{
		SERVER.OnIsSupportedItemFormat(result,error);/* Call the callback method for clip format checking*/
	}
	else if(frompage=="audiolist")
	{
			
			SERVER.OnGetAudioList (result,error);/* Call the callback method to load audio */
	}
	else if(frompage=="audiosublist")
	{
			
			SERVER.OnGetAudioSubSubList (result,error);/* Call the callback method for loading sublist of audio*/
	}
	
}

/* 
* Its a very important and common method for every event. 
* Returns response from handler class. 
* It is a call back method for sendMessageAuth.
* It checks a commandKey, for resulting listeners.
* It gives result and error object for call bcakc method for evenry call.
*/


SERVER.OnMessageAuth = function( commandKey, data )
{
    if (data==null) data = {"result":null,"error":{"level":-1,"errorMessage":"internal error", "errorCode":999 }};

    LOGGER.trace("OnMessageAuth.result:" + commandKey, data.result, "aqua");
    LOGGER.trace("OnMessageAuth.error:" + commandKey, data.error, data.error==null ?"aqua": "lightcoral");

    var error = data.error, result = data.result;
	
	//alert("result"+JSON.array(result));
    if (result == "null") result = null;
    
	var listenerName = this.listeners[commandKey];
	
    var listener = this[listenerName];
    
    if ( listener == null ) return;
    
   
    try
    {
        listener.call(this, result, error, data.data);
    }
    catch( e )
    {
        LOGGER.error(e.message, e);
    }
	
}

/* 
* Map for server object.
* It is a key-value pair for every method.
* It is a collenction name of request and callback method. 
*/

SERVER.listeners =
{
    "commandGetItemHtml"        : "OnGetItemHtml",
    "commandGetStyleHtml"       : "OnGetStyleHtml",
    "commandGetPreviewHtml"     : "OnGetPreviewHtml",
    "commandGetMuveeHtml"       : "OnGetMuveeHtml",

    "commandGetStyles"          : "OnGetStyles",
    "commandGetStyle"           : "OnGetStyle",
    "commandGetItems"           : "OnGetItems",
    "commandGetMoveeItem"       : "OnGetMoveeItem",
    "commandGetItem"            : "OnGetItem",
    "commandConvert"            : "OnConvert",
    "commandGetJob"             : "OnGetJob",
    "commandGetStatus"          : "OnGetStatus",
    "commandPurchase"           : "OnPurchase",

    "commandSetMetadata"        : "OnSetMetadata",
    "commandComment"            : "OnComment",
    "commandAbuse"              : "OnAbuse",
    "commandShareItem"          : "OnShareItem",
    "commandShareFeed"          : "OnShareFeed",

    "commandRetry"              : null,
    "commandCancel"             : null,
    "commandPause"              : null,
    "commandResume"             : null,

    "commandDeleteItem"         : "OnDeleteItem",
    "commandDeleteChannel"      : "OnDeleteChannel",
    "commandVote"               : "OnVote",
    "commandGetItemCount"       : "OnGetItemCount",

    "commandSignUpPrepare"      : "OnSignUpPrepare",
    "commandSignUp"             : "OnSignUp__private",
    "commandSignIn"             : "OnSignIn__private",
    "commandSignOut"            : "OnSignOut__private",
    "commandGetFeedByEmail"     : "OnGetFeedByEmail",
    "commandForgotPassword"     : "OnForgotPassword",

    "commandChangePassword"     : "OnChangePassword",
    "commandGetGroups"          : "OnGetGroups",
    "commandCreateGroup"        : "OnCreateGroup",
    "commandRenameGroup"        : "OnRenameGroup",
    "commandDeleteGroup"        : "OnDeleteGroup",
    "commandInviteUser"         : "OnInviteUser",
    "commandGetGroupMembers"    : "OnGetGroupMembers",
    "commandMoveItem2Group"     : "OnMoveItem2Group",
    "commandRemoveMember"       : "OnRemoveMember",
    "commandUnsubscribeMember"  : "OnUnsubscribeMember",
    "commandSubscribeMember"    : "OnSubscribeMember",
    "commandGetMembership"      : "OnGetMembership",
    "commandGetGroupType"       : "OnGetGroupType",
    "commandGetFutureGroups"    : "OnGetFutureGroups",
    "commandGetFutureMembers"   : "OnGetFutureMembers",
    "commandCancelFutureMember" : "OnCancelFutureMember",
    "commandStartPurchase"      : "OnStartPurchase",
    "commandStartPurchaseItem"  : "OnStartPurchaseItem",
    "commandGetPremiumInfo"     : "OnGetPremiumInfo",
    "commandGetChannelInfo"     : "OnGetChannelInfo",

    "commandFoundOpenIDServer"  : "OnFoundOpenIDServer",   //post
    "commandAnswerOpenIDServer" : "OnAnswerOpenIDServer", //get for servlet
    "commandGetNumberOfSubscriptions" : "OnGetNumberOfSubscriptions", 
    "getEncodePassword" : "OnEncodePassword", //add by sumit
    "getRequestKeyByEmail" : "OnRequestKeyByEmail", //add by sumit
    "signIn" : "OnSignIn", //add by sumit
    "completeRegistration":"OnCompleteRegistration",
    "changePassword":"OnChangePassword",
    "createChannel":"OnCreateChannel",
    "shareWithFirends":"OnShareWithFirends",
    "getItems":"OnGetItems",
    "editItems":"OnEditItems",
    "shareClip":"OnShareClip",
    "deleteItems":"OnDeleteItems",
    "commandGetNumberOfUserEventChannels"  :"onGetNumberOfUserEventChannels", //add by Jitendra
    "commandGetUserEventChannels"     : "onGetUserEventChannels",//add by Jitendra
	"commandGetNumberOfUserLiveChannels"  :"onGetNumberOfUserLiveChannels", //add by Jitendra
    "commandGetUserLiveChannels"     : "onGetUserLiveChannels",//add by Jitendra
    "commandGetUserOwnChannels"     : "onGetUserOwnChannels",//add by swapnil
    "commandGetUserMembershipChannels" : "onGetUserMembershipChannels",//add by swapnil
    "commandGetSubscriptions"    : "onGetSubscriptions",//add by swapnil
    "commandGetUserSubscriptions": "onGetUserSubscriptions",//add by swapnil
    "commandGetUnsubscribe"      : "onGetUnsubscribe",//add by swapnil
    "commandGetNumberOfUserSubscriptions" : "onGetNumberOfUserSubscriptions", //add by swapnil
    "commandGetNumberOfUserOwnChannels"  :"onGetNumberOfUserOwnChannels", //add by swapnil
    "commandGetNumberOfPublicChannels"   : "onGetNumberOfPublicChannels",//add by swapnil

   "commandGetNumberOfNewPublicRecentChannels"       : "onGetNumberOfNewPublicRecentChannels",//add by Jitendra dated 24/07/2008
   "commandGetNumberOfNewPublicMostViewedChannels"   : "onGetNumberOfNewPublicMostViewedChannels",//add by Jitendra dated 25/07/2008
   "commandGetNumberOfNewPublicTopRatedChannels"     : "onGetNumberOfNewPublicTopRatedChannels",//add by Jitendra dated 25/07/2008
   "commandGetNumberOfChannelFromCategory"           : "onGetNumberOfChannelFromCategory",//add by Jitendra dated 25/07/2008

    "commandGetPublicChannels"  : "onGetPublicChannels", //add by swapnil
   "commandGetNewPublicChannels"  : "onGetNewPublicChannels", //add by Jitendra dated 24/07/2008
    "commandGetPublicFreshChannels":"onGetPublicFreshChannels", //add by swapnil
    "commandGetNumberOfPublicFreshChannels" : "onGetNumberOfPublicFreshChannels",//add by swapnil
    "commandGetNumberOfUserMembershipChannels" : "onGetNumberOfUserMembershipChannels", //add by swapnil
    "commandGetSubscribe" :"onGetSubscribe",        //add by swapnil
    "getChannel":"OnGetChannel",	// sameer
    "getComments":"OnGetComments",  // sameer
    "postComment":"OnPostComment",  // sameer
    "getChannelItems":"OnGetChannelItems", //sameer
    
    "getNumberOfChannelItems" : "onGetNumberOfChannelItems", //swapnil
     "getChannelClipsUpdate"  : "OnGetChannelClipsUpdate", //Jitendra Gupta for clipUpdate.jsp
     
    "search":"OnSearch", 
    "deleteChannel":"OnDeleteChannel", //sumit
    "inviteFriends":"OnInviteFriends", //sumit
    "manageMembers":"OnManageMembers", //sumit
    "deleteMember":"onDeleteMember", //sumit
    "requestToJoin":"OnRequestToJoin", //sumit
    "moveClip":"OnMoveClip", //sumit
    "getJoinRequest":"OnGetJoinRequest", //sumit
    "getInviteRequest":"OnGetInviteRequest", //sumit
    "reportAbuse":"OnReportAbuse", //sumit
    "getUserChannels":"OnGetUserChannels", //sumit
    "deleteClip":"OnDeleteClip", //sumit
    "updateChannel":"OnUpdateChannel", //sumit
    "sendJoinRequest":"onSendJoinRequest",//swapnil
    "getUsersOwnChannels":"onGetUsersOwnChannels",//swapnil
    "getUserSubscriptions":"onGetSubscription",//swapnil
    "getEditChannel":"OnGetEditChannel",//swapnil
    "getReportAbuse":"onGetReportAbuse",//swapnil
    "getPublicChannel":"onGetPublicChannel",//swapnil
	
    "checkUsername":"OnCheckUsername",//swapnil
    "getChannels":"OnGetChannels",//swapnil
    "getClips":"OnGetClips",//swapnil
    "getClipsCount":"OnGetClipCount",//swapnil
    "getChannelsCount":"OnGetChannelCount",//swapnil
    "rateItem":"OnRateItem",//swapnil
    "getNumberOfItems":"OnGetNumberOfItems",
    "getUserMembership":"onGetUserMember",
    "acceptInvitation":"OnAcceptInvitation",
    "removeMember":"onRemoveMember",
    "getOriginalUrl":"OnGetOriginalUrl",
    "commandDeleteComment":"onDeleteComment",
    "commandGetAudioList":"OnGetAudioList", // muvee mix 
    "commandGetAudioSubList":"OnGetAudioSubList", // muvee mix 
    "commandGetAudioSubSubList":"OnGetAudioSubSubList", // muvee mix
    "commandGetUserOwnChannelList":"OnGetUserOwnChannelList",//muvee mix to get channels
    "commandGetChannelClips":"OnGetChannelClips",//,munna
    "getNumberOfComments":"onGetNumberOfComments",
    "getSecretQuestion":"onGetSecretQuestion",//swapnil
    "getUserExistOrNot":"onGetUserExistOrNot",//swapnil
    "resetPassword":"onResetPassword",
    "createCategory":"OncreateCategory",
    "getJobList":"OnGetJobList",
    "checkStatus":"OnCheckStatus",
    "updateUser":"OnUpdateUser" ,
    "feedback":"Onfeedback",
    "getMuveeStyles":"ongetMuveeStyles",
    "getPublishURL":"onGetPublishURL",    //swapnil
    "commandGetPremiumClips":"OnGetPremiumClips",
    "getSearch":"OnGetSearch",
    "importTrack":"OnImportTrack",
    "isSupportedFormat":"OnIsSupportedFormat",//munna
    "isSupportedItemFormat":"OnIsSupportedItemFormat",//munna
    "isSupportedAudioFormat":"OnIsSupportedAudioFormat",//munna
    "commandGetStyleList":"onGetStyleList",
    "getDefaultChannel":"onGetDefaultChannel", //swapnil
    "getTypeOfUser":"onGetTypeOfUser",//swapnil
   "addEmail":"OnaddEmail",
    "PhoneOrEmailInfo":"onPhoneOrEmailInfo",
    "completeAddNewEmail":"onCompleteAddNewEmail",// swapnil
     "removeEmailPhone":"onRemoveEmailPhone",
    "commandGetPhoneCarriers":"onGetPhoneCarriers",
    "getSupportedCarriers":"onGetSupportedCarriers",
    "AddCellPhone":"onAddCellPhone",
    "completeAddCellPhone":"onCompleteAddCellPhone",
    "getFileExtensions":"OnGetFileExtensions",//munna
    "removeFailedMovies":"OnRemoveFailedMovies", //munna
    "getNumberOfComments":"onGetNumberOfComments",
  /*  "getAllMimeTypes":"OnGetAllMimeTypes",//munna */
  
  "commandGetPublicRecentChannels":"onGetPublicRecentChannels",//kavita
"commandGetPublicMostViewedChannels":"onGetPublicMostViewedChannels",//kavita
"commandGetPublicTopRatedChannels":"onGetPublicTopRatedChannels",//kavita
"commandGetNumberOfTopChannels":"onGetNumberOfTopChannels",//kavita
"commandGetNumberOfMostViewedChannels":"onGetNumberOfMostViewedChannels",//kavita
"commandGetNumberOfRecentChannels":"onGetNumberOfRecentChannels",//kavita
"getChannelForClip":"ongetChannelForClip",
	"getPublisherChannel":"onGetPublisherChannel",
	"getPublisherSubscribeChannel":"onGetPublisherSubscribeChannel",
	"getNumberOfPublisherChannel":"onGetNumberOfPublisherChannel",
	"getNumberOfPublisherSubscriptions":"onGetNumberOfPublisherSubscriptions",
       "getChannelCategories":"onGetChannelCategories", //kavita
		"commandGetNumberOfCategories":"onGetNumberOfCategories",
		"commandGetCategories":"onGetCategories",
		"commandGetNumberOfCategoryChannel":"onGetNumberOfCategoryChannel",
		"commandGetChannelCategory":"onGetChannelCategory",
		"commandShowAllChannelsOfCategory":"onShowAllChannelsOfCategory",
			"update":"onUpdate",
			"getAllCategory":"onGetAllCategory",
			"getChannelFromCategory":"onGetChannelFromCategory",
			"getUserInformation":"onGetUserInformation",
			"getUserType":"onGetUserType",
		   "getChannelCategoriesByParentId" : "onGetChannelCategoriesByParentId",
		  "getItemsForLeader":"OnGetItemsForLeader",
			"getZingChannelCategories":"onGetZingChannelCategories", // add ny swapnil for zing
             "commandGetZingUserOwnChannels"     : "onGetUserZingOwnChannels",//add by swapnil for zing
              "getItemsForChannel":"onGetItemsForChannel",  //kavita
			  "getIndianIdolChannelCategories":"onGetIndianIdolChannelCategories",
"commandGetSlideshows" : "onGetSlideshows", // add by swapnil
             
    "end":null
};

 /**
 * Method for getting slideshows
 */
 SERVER.commandGetSlideshows = function(groupAlias,channelAlias,maxShows,sortBy,profileName)
 {
    this.sendMessageAuth("commandGetSlideshows",{cmd:"discovery.getSlideshows","groupAlias":groupAlias,"channelAlias":channelAlias,"maxShows":maxShows,"sortBy":sortBy,"profileName":profileName},true);
 }


/*getting the categories for creting a channel with one of those categories*/
SERVER.getIndianIdolChannelCategories=function(offst,cnt,parentId)
{
	this.sendMessageAuth("getIndianIdolChannelCategories",{cmd:"category.getCategories","parentId":parentId,"offset":offst,"count":cnt},true);
}

/*
 * Method Call For Aditis Dummy Item Page
 */
SERVER.getItemsForChannel = function(channelAlias)
{
	this.sendMessageAuth("getItemsForChannel", {cmd:"item.getItems","offset":"0","count":"-1","ordering":"top_rated","channelAlias":channelAlias,"profileName":"FlashVideo"} , true);
}



/*getting the categories for creting a channel with one of those categories in zing Module*/
SERVER.getZingChannelCategories=function(offst,cnt){
	this.sendMessageAuth("getZingChannelCategories",{cmd:"category.getCategories","parentId":"ZING","offset":offst,"count":cnt},true);
}

/* 
* Request Method for getting zing user own channels .
* paramter is offset : starting index, val : for pagination index. , filter : owner/membership.
*/

SERVER.commandGetZingUserOwnChannels = function(offset,val,filter)
{
	
	STORAGE.setOffsetVal(offset);
	var p= STORAGE.getMyownPagesVal();// jitendra
	document.getElementById("pageLinkMyownBottom").style.display="none";
	        var username = STORAGE.getUserName();
	 for(var i =0; i<20; i++){
				document.getElementById("myown"+i).style.display="none";
	           }
				
			var link="";
		
			var jumpNext = "";
				jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 20 * (offset-1);
			
			
						link=link+"<a id='prevOwn' href=javascript:SERVER.commandGetZingUserOwnChannels("+eval(offset-1)+","+jumpNext+",'owner'); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=offset+5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=p && i > 0){
						if(i == offset){
						link = link+"<a id='ownLink"+i+"' href=javascript:SERVER.commandGetZingUserOwnChannels("+eval(i)+","+eval(jumpNext)+",'owner'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='ownLink"+i+"' href=javascript:SERVER.commandGetZingUserOwnChannels("+eval(i)+","+eval(jumpNext)+",'owner'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
		
			var last=myownPages%5;
			last=last-1;
			link=link+"<a id='nextOwn' href=javascript:SERVER.commandGetZingUserOwnChannels("+eval(offset+1)+","+eval(jumpNext)+",'owner'); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			//document.getElementById('pageLinkSubBottom').innerHTML=link;
			
			document.getElementById("pageLinkMyownBottom").innerHTML=link
				
			jumpNext = i;
			
			var current = "ownLink"+offset;
			
			
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 

			if(offset <= 1){
				
				document.getElementById('prevOwn').removeAttribute('href');
				document.getElementById('prevOwn').className='chdisabled';
							}
			
			if(offset >= myownPages){
				
				document.getElementById('nextOwn').removeAttribute('href');
				document.getElementById('nextOwn').className='chdisabled';
				
			}
			this.sendMessageAuth("commandGetZingUserOwnChannels",{cmd:"channel.getUserChannels","user":username,"filter":filter,"offset":offset4,"count":"20"},true);
			
                	/* Logic for creating pagination end */
					
        	
		 setoffst=filter+":"+val+":"+offset;	
	
	
}


SERVER.getChannelCategoriesByParentId = function(offst,cnt,parentId)
{
		this.sendMessageAuth("getChannelCategoriesByParentId",{cmd:"category.getCategories","parentId":parentId,"offset":offst,"count":cnt,"parentId":parentId},true);

}


/*get Channel Item Info for clipUpdate page*/
SERVER.getChannelClipsUpdate=function(offset,alias,order,val)
{        
	
	this.sendMessageAuth("getChannelClipsUpdate",{cmd:"item.getItems","offset":offset, "count":"10", "ordering":order, "channelAlias":alias, "profileName":"FlashVideo"},true);
	
}







/* get user general info. */
SERVER.getUserInformation=function(owner){

  this.sendMessageAuth("getUserInformation",{cmd:"user.getUserInfoByLogin","login":owner},true);
}
/* get channel from selected category */
SERVER.getChannelFromCategory=function(catid){
this.sendMessageAuth("getChannelFromCategory",{cmd:"channel.getChannelsByCategory","categoryId":catid,"offset":0,"count":-1},true);
}

/**gets the categories**/
SERVER.getAllCategory=function(){
	this.sendMessageAuth("getAllCategory",{cmd:"category.getCategories","parentId":"UMUNDO","offset":0,"count":-1},true);
}

/**Method is called from view_chanel_template.jsp for showing the channels by categories**/
SERVER.commandShowAllChannelsOfCategory=function(id,offst,cnt){
	this.sendMessageAuth("commandShowAllChannelsOfCategory",{cmd:"channel.getChannelsByCategory","categoryId":id,"offset":offst,"count":cnt},true);
}

/**Gets the number of channels for the category id.**/
SERVER.commandGetNumberOfCategoryChannel=function(id){
	this.sendMessageAuth("commandGetNumberOfCategoryChannel",{cmd:"channel.getNumberOfChannelsByCategory","categoryId":id},true);
}

/**gets the categories**/
SERVER.commandGetCategories=function(offst,cnt){
	this.sendMessageAuth("commandGetCategories",{cmd:"category.getCategories","parentId":"UMUNDO","offset":offst,"count":3},true);
}

/*gets the total number of categories.*/
SERVER.commandGetNumberOfCategories=function(){
this.sendMessageAuth("commandGetNumberOfCategories",{cmd:"category.getNumberOfCategories","parentId":"UMUNDO"},true);
}


/*getting the categories for creting a channel with one of those categories*/
SERVER.getChannelCategories=function(offst,cnt){
	this.sendMessageAuth("getChannelCategories",{cmd:"category.getCategories","parentId":"UMUNDO","offset":offst,"count":cnt},true);
}

/* Request method for getting number of publisher subscribe channel */

SERVER.getNumberOfPublisherSubscriptions=function(publisher){
         this.sendMessageAuth("getNumberOfPublisherSubscriptions",{cmd:"channel.getNumberOfUserSubscriptions","user":publisher},true);
}


/* Request method for getting number of publisher channel */

SERVER.getNumberOfPublisherChannel=function(publisher){
         this.sendMessageAuth("getNumberOfPublisherChannel",{cmd:"channel.getNumberOfUserChannels","user":publisher,"filter":"owner"},true);
}


/* Request method for getting publisher subscribe channel  */
SERVER.getPublisherSubscribeChannel=function(offset,val,publisher){
        document.getElementById("pageLinkBottom").style.display="none";
	
			
	/*for(var i =0; i<10; i++){
				document.getElementById("publisher_subscription"+i).style.display="none";
	    }*/
			
		var link="";
		
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 10 * (offset-1);
			
		
						link=link+"<a id='publisher_prevSub' href=javascript:SERVER.getPublisherSubscribeChannel("+eval(offset-1)+","+jumpNext+",'"+publisher+"'); class='chactive'>Prev</a>&nbsp;";
			
				for(var i=jumpNext;i<eval(jumpNext+5);i++){
				
					if(i<=publisher_subscriptionPages && i > 0){
						if(i == offset){
						link = link+"<a id='publisher_subs"+i+"' href=javascript:SERVER.getPublisherSubscribeChannel("+eval(i)+","+eval(jumpNext)+",'"+publisher+"'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='publisher_subs"+i+"' href=javascript:SERVER.getPublisherSubscribeChannel("+eval(i)+","+eval(jumpNext)+",'"+publisher+"'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			var last=publisher_subscriptionPages%5;
			last=last-1;
			link=link+"<a id='publisher_nextSub' href=javascript:SERVER.getPublisherSubscribeChannel("+eval(offset+1)+","+eval(jumpNext)+",'"+publisher+"'); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLinkBottom').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "publisher_subs"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('publisher_prevSub').removeAttribute('href');
				document.getElementById('publisher_prevSub').className='chdisabled';
							}
			
			if(offset >= publisher_subscriptionPages){
				
				document.getElementById('publisher_nextSub').removeAttribute('href');
				document.getElementById('publisher_nextSub').className='chdisabled';
				
			}
                	/* Logic for creating pagination end */
					
   
	this.sendMessageAuth("getPublisherSubscribeChannel",{cmd:"channel.getUserSubscriptions","user":publisher,"offset":offset4,"count":"10"});

       //this.sendMessageAuth("getPublisherSubscribeChannel",{cmd:"channel.getUserSubscriptions","user":publisher,"offset":"0","count":"-1"});
}



/* Request method for getting publisher channel  */
SERVER.getPublisherChannel=function(offset,val,publisher){
	
     STORAGE.setOffsetVal(offset);
	var p= STORAGE.getMyownPagesVal();// jitendra
	document.getElementById("LinkPublisher").style.display="none";
	        //var username = STORAGE.getUserName();
	 for(var i =0; i<10; i++){
				document.getElementById("publisher_own"+i).style.display="none";
	           }
				
			var link="";
		
			var jumpNext = "";
				jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 10 * (offset-1);
			
			
						link=link+"<a id='prevpublisher_own' href=javascript:SERVER.getPublisherChannel("+eval(offset-1)+","+jumpNext+",'"+publisher+"'); class='chactive'>Prev</a>&nbsp;";
			
				for(var i=jumpNext;i<eval(jumpNext+5);i++){
				
					if(i<=p && i > 0){
						if(i == offset){
						link = link+"<a id='publisher_ownLink"+i+"' href=javascript:SERVER.getPublisherChannel("+eval(i)+","+eval(jumpNext)+",'"+publisher+"'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='publisher_ownLink"+i+"' href=javascript:SERVER.getPublisherChannel("+eval(i)+","+eval(jumpNext)+",'"+publisher+"'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
		
			var last=publisherOwnPages%5;
			last=last-1;
			link=link+"<a id='nextpublisher_own' href=javascript:SERVER.getPublisherChannel("+eval(offset+1)+","+eval(jumpNext)+",'"+publisher+"'); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			//document.getElementById('pageLinkSubBottom').innerHTML=link;
			
			document.getElementById("LinkPublisher").innerHTML=link
				
			jumpNext = i;
			
			var current = "publisher_ownLink"+offset;
			
			
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/


			if(offset <= 1){
				
				document.getElementById('prevpublisher_own').removeAttribute('href');
				document.getElementById('prevpublisher_own').className='chdisabled';
							}
			
			if(offset >= publisherOwnPages){
				
				document.getElementById('nextpublisher_own').removeAttribute('href');
				document.getElementById('nextpublisher_own').className='chdisabled';
				
			}
			this.sendMessageAuth("getPublisherChannel",{cmd:"channel.getUserChannels","user":publisher,"filter":"owner","offset":offset4,"count":"10"},true);
			
                	/* Logic for creating pagination end */


     //this.sendMessageAuth("getPublisherChannel",{cmd:"channel.getUserChannels","user":publisher,"filter":"owner","offset":"0","count":"-1"});
}



	/* This method for getting data about channel for search result */

	SERVER.getChannelForClip=function(alias){
		this.sendMessageAuth("getChannelForClip",{cmd:"channel.getChannel","channelAlias":alias});
	}

/* This method is calling method for removing failed movies.*/
SERVER.removeFailedMovies=function()
{
//alert("Test alert inside removeFailedMovies");
this.sendMessageAuth("removeFailedMovies",{cmd:"muvee.cleanFailedMuvees"},true);
}
SERVER.AddCellPhone=function(cell_value,name_carrier,phone_code){
	//alert("no is..."+cell_value);
	//alert("carrier is.."+name_carrier);
	//alert(phone_code);
	var phoneNo=phone_code+cell_value;
	this.sendMessageAuth("AddCellPhone",{cmd:"user.requestKeyToAddPhone","phoneNumber":phoneNo,"carrierName":name_carrier},true);
}

SERVER.getSupportedCarriers=function(){
	this.sendMessageAuth("getSupportedCarriers",{cmd:"phone.getSupportedCountries"},true);
}


SERVER.commandGetPhoneCarriers=function(value){

	this.sendMessageAuth("commandGetPhoneCarriers",{cmd:"phone.getSupportedCarriers","countryCode":value},true);
}



/*
* Request method adding new email in existing account.
*/
SERVER.addEmail=function(add_value){
	var url=SESSION.domain+"?newEmail="+add_value+"&key=%key%&welcome=false&fromlogout=true"
	this.sendMessageAuth("addEmail",{cmd:"user.requestKeyToAddEmail","email":add_value,"callbackUrlTemplate":url},true);
}

/* 
*  Method for getting type for given user/ login.
*  type of users are 
- "ut_registered" - fully registered user.
- "ut_unregistered" - partly registered user. Account of this user exists, but user never complete registration process.
- "ut_openId" - Not implemented yet.
*/

SERVER.getTypeOfUser=function(login){
		              
                   this.sendMessageAuth("getTypeOfUser", {cmd:"user.getUserType","login":login,"groupAlias":"umundo"},true);
	   }
	
/* 
*  Method for getting default channels for given user/ login.
*  it requires 3 parameter i.e. filter must be owner ,offset and count if for getting channels from means offset and to    means count.
*/

SERVER.getDefaultChannel=function(filter,offset,count){
		
  this.sendMessageAuth("getDefaultChannel", {cmd:"channel.getChannels","filter":filter,"offset":offset,"count":count},true);
	}

/* 
*  Method for getting categories of styles.
*  it requires 3 parameter i.e. 
   -parrentId -Unique identifier of the category's (hierarchically) parent. May be empty for root categories.,offset   	     and count it for getting categories from measn offset and to    means count.
*/


SERVER.commandGetStyleList=function(offset,ct,parentId){
   this.sendMessageAuth("commandGetStyleList", {cmd:"category.getCategories","parentId":parentId,"offset":offset,"count":ct},true);
}

/*
* Request method for getting file supported extensions for local mechine.
*/
SERVER.getFileExtensions=function()
 {
	// alert("testalert: before request1");
 //this.sendMessageAuth("getFileExtensions",{cmd:"muvee.getSupportedFilesExtensions"},true);
 this.sendMessageAuth("getFileExtensions",{cmd:"muvee.getSupportedFilesExtensions","majorMimeFilter":"image|video"},true);
 //alert("testalert: after request1");
}

/*
* Request method for getting all supported mime-types for checking items uploaded from umundo.
* This is not used.
*/
/* SERVER.getAllMimeTypes=function()
 {
	// alert("testalert: before request1");
// this.sendMessageAuth("getAllMimeTypes",{cmd:"muvee.getSupportedMimeTypes","majorMimeFilter":"image|video"},true);
 //alert("testalert: after request1");
}*/

/*
* Request method for checking file format for local mechine.
* In this method , request call is synchronous .
*/
/*SERVER.isSupportedFormat=function(filename)
 {
	// alert("testalert: before request1");
 //this.sendMessageAuthSynch("isSupportedFormat",{cmd:"muvee.isMuveeSupportedFile",'fileName':filename},true,"fileformat");
 //alert("testalert: after request1");
}*/

/*
* Request method for checking item format for Umundo
* In this method , request call is synchronous .
*/
/* SERVER.isSupportedItemFormat=function(itemguid)
 {
	//alert("testalert: before request2");
 //this.sendMessageAuthSynch("isSupportedItemFormat",{cmd:"muvee.isMuveeSupportedItem",'itemGuid':itemguid},true,"clipformat");
 //alert("testalert: after request2");
 }*/

/*
* Request method for checking audio format uplodaded from local mechine
*/
SERVER.isSupportedAudioFormat=function()
 {
 //this.sendMessageAuth("isSupportedAudioFormat",{cmd:"muvee.getSupportedMimeTypes"},true);
 this.sendMessageAuth("isSupportedAudioFormat",{cmd:"muvee.getSupportedFilesExtensions","majorMimeFilter":"audio"},true);
} 

/*
* Request method for getting premium clips for given login.
*/

 SERVER.commandGetPremiumClips=function(){
		 	var username=STORAGE.getUserName();
           this.sendMessageAuth("commandGetPremiumClips",{cmd:"muvee.getPremiumClips","user":username},true);

	 }

/*
* Request method for publishing clips/media through given url.
* Parameters- fileitem : URl fo clips.
              title    : title for clips
              desc     : description for clip.
              tags     : tags for clip
              channelAlias: alias of channel where user want to publish clip.
*/

SERVER.getPublishURL=function(fileitem,title,desc,tags,channelAlias){
		
                   this.sendMessageAuth("getPublishURL", {cmd:"item.transload", "url":fileitem, "title":title,"description":desc,"tags":tags,"channelAlias":channelAlias }, true)
	}

/*
* Request method for getting styles for given category "stylecategory".
*/
SERVER.getMuveeStyles=function(stylecategory){
		var username=STORAGE.getUserName();
            this.sendMessageAuth("getMuveeStyles", {cmd:"muvee.getStyles", "category":stylecategory},true);

	}

/*
* Request method for creating category in database.
*/
SERVER.createCategory=function(title,description,guid,parentId){

   this.sendMessageAuth("createCategory",{cmd:"category.createCategory","category":{"title":title,"description":description,"parentId":parentId}},true);
}
/*
* Response/callback method for creating category in database.
* Returns structure of created category is being used in kma.jsp.
*/
SERVER.OncreateCategory=function(result,error){
	alert("On Create caegory");
	alert("result"+result);
	alert("error"+JSON.array(error));
}

/*
* Request method for getting status of mixing clips.
*/

SERVER.getJobList=function(){
   this.sendMessageAuth("getJobList",{cmd:"muvee.getJobList"},true);
}


SERVER.checkStatus=function(jobid){
this.sendMessageAuth("checkStatus",{cmd:"muvee.checkStatus","jobId":jobid},true);
}

/*
* Request method for getting number of comments related to given channel.
*/
SERVER.getNumberOfComments=function(alias){
        this.sendMessageAuth("getNumberOfComments",{cmd:"channel.getNumberOfComments","channelAlias":alias},true);
}
/*
* Request method for getting own channels of logged in user.
*/
SERVER.getUserChannels=function(){
		var user = STORAGE.getUserName();
  		this.sendMessageAuth("getUserChannels",{cmd:"channel.getUserChannels","user":user,"filter":"owner","offset":"0","count":"-1"},true);
  	
}
/*
* Request method for getting own channels of logged in user.
* This is being call from channelpopup to display the channels
*/
SERVER.commandGetUserOwnChannelList=function()
{	
	//alert("commandGetUserOwnChannelList");
	var username = STORAGE.getUserName();
	//alert("username="+username);
	this.sendMessageAuth("commandGetUserOwnChannelList",{cmd:"channel.getUserChannels","user":username,"filter":"owner","offset":"0","count":"-1"},true);
	
}

/*
* Request method for getting clips for selected channel for logged in user.
* This is being call from channelpopup to display the clips of selected channels
*/
SERVER.commandGetChannelClips=function(alias)
{ 	
	this.sendMessageAuth("commandGetChannelClips", {cmd:"item.getItems","offset":"0","count":"-1","ordering":"top_rated","channelAlias":alias,"profileName":"FlashVideo"} , true);
	
}
/*
* Request method for getting own channels of logged in user.

*/
SERVER.getUsersOwnChannels=function(){
	//alert("getUsersOwnChannels...");
	var username = STORAGE.getUserName();
	this.sendMessageAuth("getUsersOwnChannels",{cmd:"channel.getUserChannels","user":username,"filter":"owner","offset":"0","count":"-1"},true);
	//alert("getUsersOwnChannels...");
}
  
/*
* Request method for getting audio list.
* parameter -parrentId -Unique identifier of the category's (hierarchically) parent. May be empty for root categories.,offset   	     and count it for getting categories from measn offset and to    means count.
*/

SERVER.commandGetAudioList = function(offs,ct,parentId)
{
	//alert("inside commandGetAudioList..");
	//document.getElementById("qm0").innerHTML = "Loading....";
   this.sendMessageAuthSynch("commandGetAudioList", {cmd:"category.getCategories","parentId":parentId,"offset":offs,"count":ct},true,"audiolist");
}	

/*
* Request method for getting sub audio list from given category
* parameter -parrentId -Unique identifier of the category's (hierarchically) parent. May be empty for root categories.,offset   	     and count it for getting categories from measn offset and to    means count.
*/

SERVER.commandGetAudioSubList = function(offs,ct,parentId)
{
	//alert("inside commandGetAudioSubList1..");
	//document.getElementById("qm0").innerHTML = "Loading....";
   this.sendMessageAuth("commandGetAudioSubList", {cmd:"category.getCategories","parentId":parentId,"offset":offs,"count":ct},true);
}	

/*
* Request method for getting sub audio list from given category
* parameter -categoryId -Unique identifier of the category's (hierarchically) parent. May be empty for root categories.,offset   	     and count it for getting categories from measn offset and to    means count.
*/

SERVER.commandGetAudioSubSubList = function(offs,ct,categoryId)
{
   this.sendMessageAuthSynch("commandGetAudioSubSubList", {cmd:"item.getItemsByCategory","categoryId":categoryId,"offset":offs,"count":ct,"order":"recent","profileName":"FlashVideo"},true,"audiosublist");
}

/*
* Request method for sending join request for given channel.
* parameter is alias for reqested channel.
*/
SERVER.sendJoinRequest=function(alias)
{
    this.sendMessageAuth("sendJoinRequest",{cmd:"member.requestToJoin","channelAlias":alias},true);
}

/*
* Request method for getting number of channel items from given channel.
* parameter is alias for reqested channel.
*/
SERVER.getNumberOfChannelItems=function(alias)
{
	
	this.sendMessageAuth("getNumberOfChannelItems",{cmd:"item.getNumberOfItems","channelAlias":alias},true);
}

/*
* Request method for subscribing channel.
* parameter is alias for reqested channel.
*/
SERVER.commandGetSubscribe=function(alias){

    
	this.sendMessageAuth("commandGetSubscribe",{cmd:"channel.subscribe","channelAlias":alias},true);
}

/*
* Request method for getting number of public fresh in our case its a featured channels
* Parammeter is filter and value for this is "featured".
*/
SERVER.commandGetNumberOfPublicFreshChannels=function(){
	
		this.sendMessageAuth("commandGetNumberOfPublicFreshChannels",{cmd:"channel.getNumberOfPublicChannels","filter":"featured"},true);
}
/*
* Request method for getting number of public free channels
* Parammeter is filter and value for this is "free".
*/

SERVER.commandGetNumberOfPublicChannels=function(){
	
		this.sendMessageAuth("commandGetNumberOfPublicChannels",{cmd:"channel.getNumberOfPublicChannels","filter":"free"},true);
}


SERVER.commandGetNumberOfNewPublicRecentChannels=function(){
	
		this.sendMessageAuth("commandGetNumberOfNewPublicRecentChannels",{cmd:"channel.getNumberOfPublicChannels","filter":"free"},true);
}

SERVER.commandGetNumberOfNewPublicMostViewedChannels=function(){
	
		this.sendMessageAuth("commandGetNumberOfNewPublicMostViewedChannels",{cmd:"channel.getNumberOfPublicChannels","filter":"free"},true);
}
SERVER.commandGetNumberOfNewPublicTopRatedChannels=function(){
	
		this.sendMessageAuth("commandGetNumberOfNewPublicTopRatedChannels",{cmd:"channel.getNumberOfPublicChannels","filter":"free"},true);
}

SERVER.commandGetNumberOfChannelFromCategory=function(id)
{
	this.sendMessageAuth("commandGetNumberOfChannelFromCategory",{cmd:"channel.getNumberOfChannelsByCategory","categoryId":id},true);
}
/* 
* Global variable for creating paginations
*/
var currentOffset = 0;
var jumpNext = 1;

/*
* Request method for getting public channels
* Parammeter is filter and value for this is "featured".
*/

SERVER.commandGetPublicChannels=function(offset,order,val){
	         
			document.getElementById("pageLinkBottom").style.display="none";
			order1 = order; 
			jumpNext = val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset1 = 10 * (offset-1);
			var link = "<a name='first1' href=javascript:SERVER.commandGetPublicChannels("+1+",'"+order1+"',"+1+"); class='link'>First</a>|<a name='next1' href=javascript:SERVER.commandGetPublicChannels("+eval(offset+1)+",'"+order1+"',"+eval(jumpNext)+"); class='link'>Next</a>&nbsp;";
			
			if(eval(jumpPrevius-5) >= 0){
				var jump = eval(jumpPrevius-5);
				if(jump == 0){
					jump=1;
				}
			 link = link + " <a href=javascript:SERVER.commandGetPublicChannels("+eval(jump)+",'"+order1+"',"+eval(jump)+"); class='link'><<</a>&nbsp;";
			}
			
				for(var i=jumpNext;i<eval(jumpNext+5);i++){
				
					if(i<=pages && i > 0){
						if(i == offset){
						link = link+"<a name='own"+i+"' href=javascript:SERVER.commandGetPublicChannels("+eval(i)+",'"+order1+"',"+eval(jumpNext)+"); class='link' style='color:red;'>"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a name='own"+i+"' href=javascript:SERVER.commandGetPublicChannels("+eval(i)+",'"+order1+"',"+eval(jumpNext)+"); class='link'>"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			if(i <= pages){
				link = link + "<a href=javascript:SERVER.commandGetPublicChannels("+eval(jumpNext+5)+",'"+order1+"',"+eval(jumpNext+5)+"); class='link'>>></a>&nbsp;";
			}
			var last=pages%5;
			last=last-1;
			link=link+"<a name='prev' href=javascript:SERVER.commandGetPublicChannels("+eval(offset-1)+",'"+order1+"',"+jumpNext+"); class='link'>Prev</a>|<a name='last' href=javascript:SERVER.commandGetPublicChannels("+eval(pages)+",'"+order1+"',"+eval(pages-4)+"); class='link'>Last</a>"
			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLink').innerHTML=link;
			
			document.getElementById("pageLinkBottom").innerHTML=link;
			
			jumpNext = i;
			
			var current = "own"+offset;
			
			document.getElementsByName(current)[0].removeAttribute('href');
			document.getElementsByName(current)[1].removeAttribute('href');
              /*  Code for making enable and disable of paginations.*/
                    
			if(offset <= 1){
				document.getElementsByName('first1')[0].removeAttribute('href');
				document.getElementsByName('first1')[1].removeAttribute('href');
				document.getElementsByName('first1')[0].style.color='brown';
				document.getElementsByName('first1')[1].style.color='brown';
				document.getElementsByName('prev')[0].removeAttribute('href');
				document.getElementsByName('prev')[1].removeAttribute('href');
				document.getElementsByName('prev')[0].style.color='brown';
				document.getElementsByName('prev')[1].style.color='brown';
				
			}
			if(offset >= pages){
				document.getElementsByName('last')[0].removeAttribute('href');
				document.getElementsByName('last')[1].removeAttribute('href');
				document.getElementsByName('last')[0].style.color='brown';
				document.getElementsByName('last')[1].style.color='brown';
				document.getElementsByName('next1')[0].removeAttribute('href');
				document.getElementsByName('next1')[1].removeAttribute('href');
				document.getElementsByName('next1')[0].style.color='brown';
				document.getElementsByName('next1')[1].style.color='brown';
			}
                	/* Logic for creating pagination end */
		
 this.sendMessageAuth("commandGetPublicChannels",{cmd:"channel.getPublicChannels","filter":"free","order":order,"offset":offset1,"count":"10"},true);
}


SERVER.commandGetNumberOfRecentChannels=function(filter,top,period){
		this.sendMessageAuth("commandGetNumberOfRecentChannels",{cmd:"channel.getNumberOfTopChannels","filter":filter,"top":top,"period":period},true);
}

SERVER.commandGetNumberOfMostViewedChannels=function(filter,top,period){
		this.sendMessageAuth("commandGetNumberOfMostViewedChannels",{cmd:"channel.getNumberOfTopChannels","filter":filter,"top":top,"period":period},true);
}

SERVER.commandGetNumberOfTopChannels=function(filter,top,period){
		this.sendMessageAuth("commandGetNumberOfTopChannels",{cmd:"channel.getNumberOfTopChannels","filter":filter,"top":top,"period":period},true);
}



var filter2,period2;
SERVER.commandGetPublicMostViewedChannels=function(filter,order,period,offset,val){
	         
			//document.getElementById("pageLinkBottom").style.display="none";
			filter2=filter;
			period2=period;
			order2 = order; 
		var link="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 6 * (offset-1);
			
			
						link=link+"<a id='prevMost' href=javascript:SERVER.commandGetPublicMostViewedChannels('"+filter2+"','"+order2+"','"+period2+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=most_pages && i > 0){
						if(i == offset){
						link = link+"<a id='most_subs"+i+"' href=javascript:SERVER.commandGetPublicMostViewedChannels('"+filter2+"','"+order2+"','"+period2+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='most_subs"+i+"' href=javascript:SERVER.commandGetPublicMostViewedChannels('"+filter2+"','"+order2+"','"+period2+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=most_pages%5;
			last=last-1;
			link=link+"<a id='nextMost' href=javascript:SERVER.commandGetPublicMostViewedChannels('"+filter2+"','"+order2+"','"+period2+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLink_viewed').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "most_subs"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('prevMost').removeAttribute('href');
				document.getElementById('prevMost').className='chdisabled';
							}
			
			if(offset >= most_pages){
				
				document.getElementById('nextMost').removeAttribute('href');
				document.getElementById('nextMost').className='chdisabled';
				
			}
			setoffst=order+":"+period+":"+offset;
	//alert("offset in most"+setoffst);
 this.sendMessageAuth("commandGetPublicMostViewedChannels",{cmd:"channel.getTopChannels","filter":filter2,"top":order2,"period":period2,"offset":offset4,"count":"6"},true);
}

var cat_filter;
SERVER.commandGetChannelCategory=function(filter,offset,val){
	//document.getElementById("pageLinkBottom").style.display="none";
		
	
			cat_filter=filter;
			var link="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;

	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
	
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 6 * (offset-1);
			
			
						link=link+"<a id='prevCat' href=javascript:SERVER.commandGetChannelCategory('"+cat_filter+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=cats_pages && i > 0){
						if(i == offset){
						link = link+"<a id='cat_subs"+i+"' href=javascript:SERVER.commandGetChannelCategory('"+cat_filter+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='cat_subs"+i+"' href=javascript:SERVER.commandGetChannelCategory('"+cat_filter+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=cats_pages%5;
			last=last-1;
			link=link+"<a id='nextChan' href=javascript:SERVER.commandGetChannelCategory('"+cat_filter+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			
			document.getElementById('pageLink_category').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "cat_subs"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('prevCat').removeAttribute('href');
				document.getElementById('prevCat').className='chdisabled';
							}
			
			if(offset >= cats_pages){
				
				document.getElementById('nextChan').removeAttribute('href');
				document.getElementById('nextChan').className='chdisabled';
				
			}
	
	//alert("offset in most="+offset);
	this.sendMessageAuth("commandGetChannelCategory",{cmd:"channel.getChannelsByCategory","categoryId":filter,"offset":offset4,"count":"10"},true);
}





//offset,order,val
var filter1,period1;
SERVER.commandGetPublicTopRatedChannels=function(filter,order,period,offset,val){
	
			//document.getElementById("pageLinkBottom").style.display="none";
			filter1=filter;
			period1=period;
			order1 = order; 
			
	var link="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 6 * (offset-1);
			
			
						link=link+"<a id='prevSub' href=javascript:SERVER.commandGetPublicTopRatedChannels('"+filter1+"','"+order1+"','"+period1+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=top_pages && i > 0){
						if(i == offset){
						link = link+"<a id='subs"+i+"' href=javascript:SERVER.commandGetPublicTopRatedChannels('"+filter1+"','"+order1+"','"+period1+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='subs"+i+"' href=javascript:SERVER.commandGetPublicTopRatedChannels('"+filter1+"','"+order1+"','"+period1+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=top_pages%5;
			last=last-1;
			link=link+"<a id='nextSub' href=javascript:SERVER.commandGetPublicTopRatedChannels('"+filter1+"','"+order1+"','"+period1+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLink_rated').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "subs"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('prevSub').removeAttribute('href');
				document.getElementById('prevSub').className='chdisabled';
							}
			
			if(offset >= top_pages){
				
				document.getElementById('nextSub').removeAttribute('href');
				document.getElementById('nextSub').className='chdisabled';
				
			}


setoffst=order+":"+period+":"+offset;
//alert("setoffst in common.js="+setoffst);
 this.sendMessageAuth("commandGetPublicTopRatedChannels",{cmd:"channel.getTopChannels","filter":filter1,"top":order1,"period":period1,"offset":offset4,"count":"6"},true);
}
var filter3,period3;
SERVER.commandGetPublicRecentChannels=function(filter,order,period,offset,val){
	         
			//document.getElementById("pageLinkBottom").style.display="none";
			order1 = order; 
			filter3=filter;
			period3=period;
			
		var link="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 6 * (offset-1);
			
			
						link=link+"<a id='prevRecent' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=view_pages && i > 0){
						if(i == offset){
						link = link+"<a id='subs_rec"+i+"' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='subs_rec"+i+"' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=view_pages%5;
			last=last-1;
			link=link+"<a id='nextRecent' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLink').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "subs_rec"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('prevRecent').removeAttribute('href');
				document.getElementById('prevRecent').className='chdisabled';
							}
			
			if(offset >= view_pages){
				
				document.getElementById('nextRecent').removeAttribute('href');
				document.getElementById('nextRecent').className='chdisabled';
				
			}
	
	 setoffst=order+":"+period+":"+offset; 
	 
 this.sendMessageAuth("commandGetPublicRecentChannels",{cmd:"channel.getTopChannels","filter":filter3,"top":order1,"period":period3,"offset":offset4,"count":"6"},true);
}



/*
* Request method for  pagination of Public Channels it May be Recent,Top rated ,Most Viewed .
*/

SERVER.commandGetNewPublicChannels=function(filter,order,offset,val){
	        
	        document.getElementById("recentDisplay").style.display="none";
	document.getElementById("loadingImage_category").style.display="block";
	
			//document.getElementById("pageLinkBottom").style.display="none";
			order1 = order; 
			filter3=filter;
			//period3=period;
			
		var link="";
		var linkBottom="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 12 * (offset-1);
			
			 //alert("offset1");
						link=link+"<a id='prevRecent' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
						linkBottom=linkBottom+"<a id='prevRecent1' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=view_pages && i > 0){
						if(i == offset){
						link = link+"<a id='subs_rec"+i+"' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"'"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						linkBottom = linkBottom+"<a id='subs_rec1"+i+"' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"'"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='subs_rec"+i+"' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
							linkBottom = linkBottom+"<a id='subs_rec1"+i+"' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			// alert("offset2");
			
			var last=view_pages%5;
			last=last-1;
			link=link+"<a id='nextRecent' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";
           
			 link=link+"&nbsp;&nbsp;";
			linkBottom=linkBottom+"<a id='nextRecent1' href=javascript:SERVER.commandGetNewPublicChannels('"+filter3+"','"+order1+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";
            linkBottom=linkBottom+"&nbsp;&nbsp;";

			document.getElementById('pageLinkChannels').innerHTML=link;
			
			document.getElementById("pageLinkChannelsBottom").innerHTML=linkBottom;
			//document.getElementById('pageLinkChannels')..style.display="block";
			
			
			
			jumpNext = i;
			
			var current = "subs_rec"+offset;
			var current1 = "subs_rec1"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
			document.getElementById(current1).removeAttribute('href');
			document.getElementById(current1).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('prevRecent').removeAttribute('href');
				document.getElementById('prevRecent').className='chdisabled';
				document.getElementById('prevRecent1').removeAttribute('href');
				document.getElementById('prevRecent1').className='chdisabled';
							}
			
			if(offset >= view_pages){
				
				document.getElementById('nextRecent').removeAttribute('href');
				document.getElementById('nextRecent').className='chdisabled';
				document.getElementById('nextRecent1').removeAttribute('href');
				document.getElementById('nextRecent1').className='chdisabled';
			 //alert("offset3");	
			}
	
	// setoffst=order+":"+period+":"+offset; 
	 // alert("offset 4=filter3="+filter3);
 this.sendMessageAuth("commandGetNewPublicChannels",{cmd:"channel.getPublicChannels","filter":filter3,"order":order1,"offset":offset4,"count":"12"},true);
 
}


/*
* Request Method for ChannelsFromCategory pagination
*/

//offset,order,val
var cateId,period1;
SERVER.getChannelFromCategory=function(cateId,offset,val){
	
	   document.getElementById("recentDisplay").style.display="none";
	document.getElementById("loadingImage_category").style.display="block";
			//document.getElementById("pageLinkBottom").style.display="none";
			cateId=cateId;
			//period1=period;
		//	order1 = order; 
			
	var link="";
	var linkBottom="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 12 * (offset-1);
			
			
					link=link+"<a id='prevSub' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			         linkBottom=linkBottom+"<a id='prevSub1' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=top_pages && i > 0){
						if(i == offset){
						link = link+"<a id='subs_cate"+i+"' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						linkBottom = linkBottom+"<a id='subs_cate1"+i+"' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						
						}else{
							link = link+"<a id='subs_cate"+i+"' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
							linkBottom = linkBottom+"<a id='subs_cate1"+i+"' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						
						}
					}
					
				}
			
			
			var last=top_pages%5;
			last=last-1;
			 link=link+"<a id='nextSub' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";
			 link=link+"&nbsp;&nbsp;";
			 linkBottom=linkBottom+"<a id='nextSub1' href=javascript:SERVER.getChannelFromCategory('"+cateId+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 linkBottom=linkBottom+"&nbsp;&nbsp;";
		
			document.getElementById('pageLinkChannels').innerHTML=link;
			document.getElementById('pageLinkChannelsBottom').innerHTML=linkBottom;
			
			
			
			jumpNext = i;
			//alert("cateId 0="+cateId);  
			
			var current = "subs_cate"+offset;
			var current1 = "subs_cate1"+offset;
		
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
			document.getElementById(current1).removeAttribute('href');
			document.getElementById(current1).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

       // alert("cateId 1="+cateId);         
			if(offset <= 1){
				
				document.getElementById('prevSub').removeAttribute('href');
				document.getElementById('prevSub').className='chdisabled';
				document.getElementById('prevSub1').removeAttribute('href');
				document.getElementById('prevSub1').className='chdisabled';
							}
			
			if(offset >= top_pages){
				
				document.getElementById('nextSub').removeAttribute('href');
				document.getElementById('nextSub').className='chdisabled';
				document.getElementById('nextSub1').removeAttribute('href');
				document.getElementById('nextSub1').className='chdisabled';
				
			}


//setoffst=order+":"+period+":"+offset;
//alert("setoffst in common.js="+setoffst);
 this.sendMessageAuth("getChannelFromCategory",{cmd:"channel.getChannelsByCategory","categoryId":cateId,"offset":offset4,"count":"12"},true);

}




var filter3,period3;
SERVER.commandGetPublicRecentChannels=function(filter,order,period,offset,val){
	         
			//document.getElementById("pageLinkBottom").style.display="none";
			order1 = order; 
			filter3=filter;
			period3=period;
			
		var link="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 6 * (offset-1);
			
			
						link=link+"<a id='prevRecent' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=view_pages && i > 0){
						if(i == offset){
						link = link+"<a id='subs_rec"+i+"' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='subs_rec"+i+"' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=view_pages%5;
			last=last-1;
			link=link+"<a id='nextRecent' href=javascript:SERVER.commandGetPublicRecentChannels('"+filter3+"','"+order1+"','"+period3+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLink').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "subs_rec"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('prevRecent').removeAttribute('href');
				document.getElementById('prevRecent').className='chdisabled';
							}
			
			if(offset >= view_pages){
				
				document.getElementById('nextRecent').removeAttribute('href');
				document.getElementById('nextRecent').className='chdisabled';
				
			}
	
	 setoffst=order+":"+period+":"+offset; 
	 
 this.sendMessageAuth("commandGetPublicRecentChannels",{cmd:"channel.getTopChannels","filter":filter3,"top":order1,"period":period3,"offset":offset4,"count":"6"},true);
}



/*
* Request method for getting public featured channels
* Parammeter is filter and value for this is "featured".
*/
SERVER.commandGetPublicFreshChannels=function(offset,val){
//  document.getElementById("pageLinkFreshBottom").style.display="none"; 
 /*      	var link="";
		var jumpNext = "";
	jumpNext=val;
	var jumpPrevius = jumpNext;
	if(jumpNext-offset == 1){
	jumpNext = offset-5;
	}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 6 * (offset-1);
			
			
						link=link+"<a id='prevFresh' href=javascript:SERVER.commandGetPublicFreshChannels("+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
						offsetTo=+offset + +5;
			}
				for(var i=start;i<eval(offsetTo);i++){
					if(i<=fresh_pages && i > 0){
						if(i == offset){
						link = link+"<a id='fresh"+i+"' href=javascript:SERVER.commandGetPublicFreshChannels("+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='fresh"+i+"' href=javascript:SERVER.commandGetPublicFreshChannels("+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=fresh_pages%5;
			last=last-1;
			link=link+"<a id='nextFresh' href=javascript:SERVER.commandGetPublicFreshChannels("+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLinkFresh').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "fresh"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
             

                 
			if(offset <= 1){
				
				document.getElementById('prevFresh').removeAttribute('href');
				document.getElementById('prevFresh').className='chdisabled';
							}
			
			if(offset >= fresh_pages){
				
				document.getElementById('nextFresh').removeAttribute('href');
				document.getElementById('nextFresh').className='chdisabled';
				
			}*/
                	/* Logic for creating pagination end */

		this.sendMessageAuth("commandGetPublicFreshChannels",{cmd:"channel.getPublicChannels","filter":"featured","order":"recent","offset":0,"count":-1},true);
}


/*  
* Request method for getting number of user own channels
*/
SERVER.commandGetNumberOfUserOwnChannels=function()
{
	var username = STORAGE.getUserName();

	//STORAGE.setWsseHeader(wsseHeader("sharefun-email-ykameshrao@gmail.com", "kamelamma"));
	this.sendMessageAuth("commandGetNumberOfUserOwnChannels",{cmd:"channel.getNumberOfUserChannels","user":username,"filter":"owner","groupAlias":"umundo"},true);
}

/*  
* Request method for getting number of user subscribed channels
*/
SERVER.commandGetNumberOfUserSubscriptions=function()
{
	var username = STORAGE.getUserName();
	
	//STORAGE.setWsseHeader(wsseHeader("sharefun-email-ykameshrao@gmail.com", "kamelamma"));
	this.sendMessageAuth("commandGetNumberOfUserSubscriptions",{cmd:"channel.getNumberOfUserSubscriptions","user":username,"groupAlias":"umundo"},true);
}

/*  
* Request method for getting number of user membership channels
*/

SERVER.commandGetNumberOfUserMembershipChannels=function(){
	var username = STORAGE.getUserName();

	//STORAGE.setWsseHeader(wsseHeader("sharefun-email-ykameshrao@gmail.com", "kamelamma"));
	this.sendMessageAuth("commandGetNumberOfUserMembershipChannels",{cmd:"channel.getNumberOfUserChannels","user":username,"filter":"member","groupAlias":"umundo"},true);
}

/*
* Request method for getting getting structure info of given channel alias.
*/
SERVER.getChannel=function(alias)
{
	//STORAGE.setWsseHeader(wsseHeader("sharefun-email-ykameshrao@gmail.com", "kamelamma"));
	this.sendMessageAuth("getChannel",{cmd:"channel.getChannel","channelAlias":alias});
	
}


/*
* Request Method for getting all comments of requesting channel.
* parameter is  channel alias.
*/
SERVER.getComments=function(alias,offset,val)
{      var link="";
		var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offsetComm = 5 * (offset-1);
			link=link+"<a id='nextComm' href=javascript:SERVER.getComments('"+commentAlias+"',"+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";
			
			
			
				for(var i=jumpNext;i<eval(jumpNext+5);i++){
				
					if(i<=comment_pages && i > 0){
						if(i == offset){
						link = link+"<a id='comm"+i+"' href=javascript:SERVER.getComments('"+commentAlias+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new'>"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='comm"+i+"' href=javascript:SERVER.getComments('"+commentAlias+"',"+eval(i)+","+eval(jumpNext)+"); class='pagination_new'>"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=comment_pages%5;
			last=last-1;
			link=link+"<a id='prevComm' href=javascript:SERVER.getComments('"+commentAlias+"',"+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>";
			 link=link+"&nbsp;&nbsp;";
			document.getElementById('comment_link').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "comm"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/
                   
			if(offset <= 1){
				
				document.getElementById('prevComm').removeAttribute('href');
				document.getElementById('prevComm').className='chdisabled';
							}
			
			if(offset >= comment_pages){
				
				document.getElementById('nextComm').removeAttribute('href');
				document.getElementById('nextComm').className='chdisabled';
				
			}
                	/* Logic for creating pagination end */
			


	this.sendMessageAuth("getComments",{cmd:"channel.getComments","channelAlias":commentAlias,offset:offsetComm,count:"5"});
}
/*
* Request Method for posting  comments for requesting channel.
* parameter is  channel alias,and comment (string).
*/
SERVER.postComment=function(alias, comment)
{
	//STORAGE.setWsseHeader(wsseHeader("sharefun-email-ykameshrao@gmail.com", "kamelamma"));
	this.sendMessageAuth("postComment",{cmd:"channel.postComment","channelAlias":alias, "comment":comment},true);
}
/*
* Request Method for getting channelItems for requesting channel in a specified order.
* Parameter offset means starting index,alias means channel alias, order : " top_rated","most_viewed","recent"
* It is being used in view_channels_template.jsp.
*/
var current_offset="";
SERVER.getChannelItems=function(offset,alias,order,val)
{            
	
	      for(var i=0;i<3;i++){
			  for(var j=0;j<3;j++){
				  document.getElementById("recent"+i+""+j).style.display="none";
	              document.getElementById("most_viewed"+i+""+j).style.display="none";
			      document.getElementById("rating"+i+""+j).style.display="none";
			  }
		  }
              /* Code for creating paginations */
	        order1 = order; 
			alias1=alias;

			jumpNext = val;
			var jumpPrevius = jumpNext;
			 var offset1 = 9 * (offset-1); 
			
			 var link="<a id='first3' href=javascript:SERVER.getChannelItems("+eval(offset-1)+",'"+alias1+"','"+order1+"',"+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			//var link = "<a id='first3' href=javascript:SERVER.getChannelItems("+1+",'"+alias1+"','"+order1+"',"+1+"); class='chactive'>First&nbsp;</a>";
			/*if(eval(jumpPrevius-5) >= 0){
				var jump = eval(jumpPrevius-5);
				if(jump == 0){
					jump=1;
				}
			 link = link + "<a href=javascript:SERVER.getChannelItems("+eval(jump)+",'"+alias1+"','"+order1+"',"+eval(jump)+"); class='chactive'><<</a>&nbsp;";
			}*/
		
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=offset+5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				   if(i<=itemPages && i > 0){
						if(i == offset){
						link = link+"<a id='link1"+i+"' href=javascript:SERVER.getChannelItems("+eval(i)+",'"+alias1+"','"+order1+"',"+eval(jumpNext)+"); class='pagination_new'>"+eval(i)+"</a>&nbsp;"
						}else{
							link = link+"<a id='link1"+i+"' href=javascript:SERVER.getChannelItems("+eval(i)+",'"+alias1+"','"+order1+"',"+eval(jumpNext)+"); class='pagination_new'>"+eval(i)+"</a>&nbsp;"
						}
					}


					/*if(i<=itemPages){
						link = link+"<a id='link1"+i+"' href=javascript:SERVER.getChannelItems("+eval(i)+",'"+alias1+"','"+order1+"',"+eval(jumpNext)+"); class='pagination_new'>"+eval(i)+"</a>&nbsp;"
					}*/
					
				}
			/*jumpNext = i;
			if(i <= itemPages){
				link = link + "<a href=javascript:SERVER.getChannelItems("+eval(jumpNext)+",'"+alias1+"','"+order1+"',"+eval(jumpNext)+"); class='chactive'>>></a>&nbsp;";
			}*/
			var last=itemPages%5;
			last=last-1;
			link=link+"<a id='last3' href=javascript:SERVER.getChannelItems("+eval(offset+1)+",'"+alias1+"','"+order1+"',"+eval(jumpNext)+"); class='chactive'>Next</a>"
			document.getElementById('viewPageLink').innerHTML=link;
			var current = "link1"+offset;
			current_offset=offset;
			if(document.getElementById(current) != null){
				document.getElementById(current).removeAttribute('href');
				document.getElementById(current).className="pagination_visited";
			}
			//document.getElementsByName(current)[1].removeAttribute('href');
			if(offset <= 1){
				
				document.getElementById('first3').removeAttribute('href');
				//document.getElementsByName('first')[1].removeAttribute('href');
				document.getElementById('first3').className="chdisabled";
				//document.getElementsByName('first')[1].style.color='brown';
				
			}
			
			if(offset >= itemPages){
				document.getElementById('last3').removeAttribute('href');
				//document.getElementsByName('last1')[1].removeAttribute('href');
				document.getElementById('last3').className="chdisabled";
				//document.getElementsByName('last1')[1].style.color='brown';
			}
			
	//MediaPlayer.setOffset(offset1);	
	
	
	this.sendMessageAuth("getChannelItems",{cmd:"item.getItems","offset":offset1, "count":"9", "ordering":order1, "channelAlias":alias1, "profileName":"FlashVideo"},true);

	if(offset1>2)
	{
	MediaPlayer.setOffset(offset1);	
	}
}


/* 
* Request Method for unsubscribing channel.
*/

SERVER.commandGetUnsubscribe=function(alias)
{
	
this.sendMessageAuth("commandGetUnsubscribe",{cmd:"channel.unsubscribe","channelAlias":alias});
}

/* 
* Request Method for getting user own channels .
* paramter is offset : starting index, val : for pagination index. , filter : owner/membership.
*/

SERVER.commandGetUserOwnChannels = function(offset,val,filter)
{
	
	STORAGE.setOffsetVal(offset);
	var p= STORAGE.getMyownPagesVal();// jitendra
	document.getElementById("pageLinkMyownBottom").style.display="none";
	        var username = STORAGE.getUserName();
	 for(var i =0; i<10; i++){
				document.getElementById("myown"+i).style.display="none";
	           }
				
			var link="";
		
			var jumpNext = "";
				jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 10 * (offset-1);
			
			
						link=link+"<a id='prevOwn' href=javascript:SERVER.commandGetUserOwnChannels("+eval(offset-1)+","+jumpNext+",'owner'); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=offset+5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=p && i > 0){
						if(i == offset){
						link = link+"<a id='ownLink"+i+"' href=javascript:SERVER.commandGetUserOwnChannels("+eval(i)+","+eval(jumpNext)+",'owner'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='ownLink"+i+"' href=javascript:SERVER.commandGetUserOwnChannels("+eval(i)+","+eval(jumpNext)+",'owner'); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
		
			var last=myownPages%5;
			last=last-1;
			link=link+"<a id='nextOwn' href=javascript:SERVER.commandGetUserOwnChannels("+eval(offset+1)+","+eval(jumpNext)+",'owner'); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			//document.getElementById('pageLinkSubBottom').innerHTML=link;
			
			document.getElementById("pageLinkMyownBottom").innerHTML=link
				
			jumpNext = i;
			
			var current = "ownLink"+offset;
			
			
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 

			if(offset <= 1){
				
				document.getElementById('prevOwn').removeAttribute('href');
				document.getElementById('prevOwn').className='chdisabled';
							}
			
			if(offset >= myownPages){
				
				document.getElementById('nextOwn').removeAttribute('href');
				document.getElementById('nextOwn').className='chdisabled';
				
			}
			this.sendMessageAuth("commandGetUserOwnChannels",{cmd:"channel.getUserChannels","user":username,"filter":filter,"offset":offset4,"count":"10"},true);
			
                	/* Logic for creating pagination end */
					
        	
		 setoffst=filter+":"+val+":"+offset;	
	
	
}


/* 
* Request Method for getting users membership channels.
*/
SERVER.commandGetUserMembershipChannels = function(offset,val)
{
	
	document.getElementById("pageLinkMembershipBottom").style.display="none";
	var username = STORAGE.getUserName();
	for(var i =0; i<10; i++){
		
				document.getElementById("membership"+i).style.display="none";
	}

			var link="";
		
			var jumpNext = "";
				jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset_mem = 10 * (offset-1);
			
			
						link=link+"<a id='prevMem' href=javascript:SERVER.commandGetUserMembershipChannels("+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			
				for(var i=jumpNext;i<eval(jumpNext+5);i++){
				
					if(i<= membershipPages&& i > 0){
						if(i == offset){
						link = link+"<a id='memLink"+i+"' href=javascript:SERVER.commandGetUserMembershipChannels("+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='memLink"+i+"' href=javascript:SERVER.commandGetUserMembershipChannels("+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
		
			var last=membershipPages%5;
			last=last-1;
			link=link+"<a id='nextMem' href=javascript:SERVER.commandGetUserMembershipChannels("+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			//document.getElementById('pageLinkSubBottom').innerHTML=link;
			
			document.getElementById("pageLinkMembershipBottom").innerHTML=link
				
			jumpNext = i;
			
			var current = "memLink"+offset;
			
			
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 

			if(offset <= 1){
				
				document.getElementById('prevMem').removeAttribute('href');
				document.getElementById('prevMem').className='chdisabled';
							}
			
			if(offset >= membershipPages){
				
				document.getElementById('nextMem').removeAttribute('href');
				document.getElementById('nextMem').className='chdisabled';
				
			}
this.sendMessageAuth("commandGetUserMembershipChannels",{cmd:"channel.getUserChannels","user":username,"filter":"member","offset":offset_mem,"count":"10"},true);
	
	  setoffst=val+":"+offset;
	
}


/* 
* Request Method for getting users subscribe channels.
*/

SERVER.commandGetSubscriptions = function()
{
	//STORAGE.setWsseHeader(wsseHeader("sharefun-email-ykameshrao@gmail.com", "kamelamma"));
	this.sendMessageAuth("commandGetSubscriptions",{cmd:"channel.getSubscriptions","offset":"0","count":"-1"});
}

/* 
* Request Method for getting users subscribe channels.
*/

SERVER.commandGetUserSubscriptions = function(offset,val)
{
	document.getElementById("pageLinkSubBottom").style.display="none";
	var username = STORAGE.getUserName();
	for(var i =0; i<10; i++){
				document.getElementById("subscription"+i).style.display="none";
	    }
		var link="";
		//var commentAlias = alias; 
			var jumpNext = "";
			jumpNext=val;
	/* Logic for creating pagination starts */		
			var jumpPrevius = jumpNext;
			if(jumpNext-offset == 1){
				jumpNext = offset-5;
			}
			if(offset-jumpNext >= 5){
				jumpNext = offset-4;
			}
			 var offset4 = 10 * (offset-1);
			
			
						link=link+"<a id='prevSub' href=javascript:SERVER.commandGetUserSubscriptions("+eval(offset-1)+","+jumpNext+"); class='chactive'>Prev</a>&nbsp;";
			
				var start=0;
			var off_six=offset%5;
			var offsetTo=6;
            if(offset>5 || off_six==0){
                    start=offset-4;
					offsetTo=offset+5;
			}
				for(var i=start;i<eval(offsetTo);i++){
				
					if(i<=subscriptionPages && i > 0){
						if(i == offset){
						link = link+"<a id='subs"+i+"' href=javascript:SERVER.commandGetUserSubscriptions("+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}else{
							link = link+"<a id='subs"+i+"' href=javascript:SERVER.commandGetUserSubscriptions("+eval(i)+","+eval(jumpNext)+"); class='pagination_new' >"+eval(i)+"</a>&nbsp;";
						}
					}
					
				}
			
			
			var last=subscriptionPages%5;
			last=last-1;
			link=link+"<a id='nextSub' href=javascript:SERVER.commandGetUserSubscriptions("+eval(offset+1)+","+eval(jumpNext)+"); class='chactive'>Next</a>&nbsp;";

			 link=link+"&nbsp;&nbsp;";
			document.getElementById('pageLinkSubBottom').innerHTML=link;
			
			
			
			jumpNext = i;
			
			var current = "subs"+offset;
			document.getElementById(current).removeAttribute('href');
			document.getElementById(current).className='pagination_visited';
              /*  Code for making enable and disable of paginations.*/

                 
			if(offset <= 1){
				
				document.getElementById('prevSub').removeAttribute('href');
				document.getElementById('prevSub').className='chdisabled';
							}
			
			if(offset >= subscriptionPages){
				
				document.getElementById('nextSub').removeAttribute('href');
				document.getElementById('nextSub').className='chdisabled';
				
			}
                	/* Logic for creating pagination end */
		//alert("offset="+offset);
		
			
       setoffst=val+":"+offset;
      
	this.sendMessageAuth("commandGetUserSubscriptions",{cmd:"channel.getUserSubscriptions","user":username,offset:offset4,count:"10"});

}
/* 
* Request Method for getting number of users subscribe channels.
*/

SERVER.commandGetNumberOfSubscriptions = function()
{
    this.sendMessageAuth("commandGetNumberOfSubscriptions", {cmd:"user.encodePassword","login":"admin123","authKey":"E7FA2A39D9054845A60C258E242AE0D09AD94A8A49F244a581D2FBE06B08F3576C88D3FB9A1745e4B831AA8A5A8590614A5BA27333A24789A1F18B015C6CB5FD"} , true);
}

/* 
* Request Method for getting muvee styels
*/

SERVER.commandGetStyles = function()
{
    this.sendMessageAuth("commandGetStyles", {cmd:"muvee.styles"} , true);
}

/* 
* Request Method for getting muvee style of specified id from list of styles.
*/

SERVER.commandGetStyle = function(id)
{
    this.sendMessageAuth("commandGetStyle", {cmd:"muvee.style",muveeStyle:id} , true);
}

/* 
* Request Method for getting channel items in specified order.
*/

SERVER.commandGetItems = function(feed, skip, count, sortby)
{
    this.sendMessageAuth("commandGetItems", {cmd:"item.getItems", "channelAlias":feed, "offset":skip, "count":count, "ordering":sortby},true );
}

/* 
* Request Method for getting item info of specified item from given channel.
* Parameter- guid: guid for item. feed : username;
*/

SERVER.commandGetItem = function(feed, guid)
{
    this.sendMessageAuth("commandGetItem", {cmd:"item.getItem", "channelAlias":feed, "itemGuid":guid });
}

/* 
* Request Method for getting muvee item info of specified item .
* Parameter- guid: guid for item. feed : username;
*/

SERVER.commandGetMoveeItem = function(feed, guid)
{
    this.sendMessageAuth("commandGetMoveeItem", {cmd:"muvee.item", "feedLongName":feed, "itemGuid":guid }, true);
}

SERVER.commandGetItemHtml = function(login)
{
    this.sendMessageAuth("commandGetItemHtml", {cmd:"muvee.itemHtml", "login":login} , true);
}

SERVER.commandGetStyleHtml = function(styleId)
{
    this.sendMessageAuth("commandGetStyleHtml", {cmd:"muvee.styleHtml", "muveeStyle":styleId} , true);
}

SERVER.commandGetPreviewHtml = function(login, itemId, styleId, jobId)
{
    this.sendMessageAuth("commandGetPreviewHtml", {cmd:"muvee.previewHtml","login":login,"itemGuid":itemId, "muveeStyle":styleId, "jobId":jobId}, true);
}

SERVER.commandGetMuveeHtml = function(login, itemId, styleId, jobId)
{
    this.sendMessageAuth("commandGetMuveeHtml", {cmd:"muvee.muveeHtml","login":login,"itemGuid":itemId, "muveeStyle":styleId, "jobId":jobId}, true);
}

SERVER.commandConvert = function(login, itemId, styleId)
{
    this.sendMessageAuth("commandConvert", {cmd:"muvee.convert","login":login,"itemGuid":itemId, "muveeStyle":styleId}, true );
}

SERVER.commandGetJob = function(login, itemId, styleId)
{
    this.sendMessageAuth("commandGetJob", {cmd:"muvee.getJob", "login":login,"itemGuid":itemId, "muveeStyle":styleId} , true);
}

SERVER.commandPurchase = function( id, info)
{
    this.sendMessageAuth("commandPurchase", UTILS.leftJoin( {cmd:"muvee.pay", "jobId":id}, info), true );
}

SERVER.commandGetStatus = function(id)
{
    this.sendMessageAuth("commandGetStatus", {cmd:"muvee.status", jobId:id}, true );
}

SERVER.commandCancel = function(id)
{
    this.sendMessageAuth("commandCancel", {cmd:"muvee.cancel", jobId:id} , true);
}

SERVER.commandPause = function(id)
{
    this.sendMessageAuth("commandPause", {cmd:"muvee.pause", jobId:id} , true);
}

SERVER.commandResume = function(id)
{
    this.sendMessageAuth("commandResume", {cmd:"muvee.resume", jobId:id} , true);
}

SERVER.commandRetry = function(id)
{
    this.sendMessageAuth("commandRetry", {cmd:"muvee.retry", jobId:id} , true);
}

SERVER.commandSetMetadata = function(job_id, title, replaceOriginal)
{
    this.sendMessageAuth("commandSetMetadata", {cmd:"muvee.setItemInfo", "jobId":job_id, "title":title, "replaceOriginal":replaceOriginal} , true);
}

SERVER.commandComment = function(sender, subject, comment)
{
    this.sendMessageAuth("commandComment", {cmd:"sendComment", "sender":sender, "subject":subject, "body": comment}, true );
}

SERVER.commandAbuse = function(sender,  comment, itemId, feed)
{
    this.sendMessageAuth("commandAbuse", {cmd:"sendAbuse", "sender":sender, "body": comment, "itemId":itemId, "feedAlias":feed} );
}

SERVER.commandShareItem = function(recipients, senderName,  comment, itemId, feed, type)
{
    this.sendMessageAuth("commandShareItem", {cmd:"shareItem", "recipients":recipients, "senderName":senderName, "body": comment, "itemId":itemId, "feedAlias":feed, "shareType":type} );
}

SERVER.commandShareFeed = function(recipients, senderName,  comment, feed)
{
    this.sendMessageAuth("commandShareFeed", {cmd:"shareFeed", "recipients":recipients, "senderName":senderName, "body": comment,  "feedAlias":feed} );
}

SERVER.commandDeleteItem = function( feed,  itemGuid)
{
    this.sendMessageAuth("commandDeleteItem", {cmd:"deleteItem", "feedLongName": feed, "itemGuid":itemGuid},true);
}

SERVER.commandDeleteChannel = function( feed)
{
    this.sendMessageAuth("commandDeleteChannel", {cmd:"deleteChannel",  "feedLongName": feed},true);
}

SERVER.commandVote = function( feed, itemGuid, rating)
{
    this.sendMessageAuth("commandVote", {cmd:"item.rate", /* "feedLongName": feed,*/ "itemGuid":itemGuid, "rating":rating },true );
}

SERVER.commandGetItemCount = function(feed)
{
    this.sendMessageAuth("commandGetItemCount", {cmd:"item.getNumberOfItems",  "channelAlias": feed },true );
}

SERVER.commandChangePassword = function(oldPassword, newPassword)
{
    this.sendMessageAuth("commandChangePassword", {cmd:"changePassword",  "oldPassword":oldPassword, "newPassword":newPassword},true );
}

SERVER.commandGetGroups = function()
{
    this.sendMessageAuth("commandGetGroups", {cmd:"groupList"},true );
}

SERVER.commandCreateGroup = function(name, description, type, guid)
{
    this.sendMessageAuth("commandCreateGroup", {cmd:"createGroup", "name":name, "description":description, "type":type, "feedShortName":guid},true );
}

SERVER.commandRenameGroup = function(feed, name, description)
{
    this.sendMessageAuth("commandRenameGroup", {cmd:"renameGroup","feedLongName": feed, "name":name, "description":description },true );
}

SERVER.commandDeleteGroup = function(feed)
{
    this.sendMessageAuth("commandDeleteGroup", {cmd:"deleteGroup", "feedLongName": feed},true );
}

SERVER.commandGetGroupMembers = function(feed)
{
    this.sendMessageAuth("commandGetGroupMembers", {cmd:"membersList", "feedLongName": feed},true );
}

SERVER.commandMoveItem2Group = function(newFeed, guid)
{
    this.sendMessageAuth("commandMoveItem2Group", {cmd:"moveItem2Group", "feedLongName": newFeed, "itemGuid":guid},true );
}

SERVER.commandInviteUser = function(feed, email)   //owner add another user
{
    this.sendMessageAuth("commandInviteUser", {cmd:"inviteUser2Group", "feedLongName": feed, "email":email},true );
}

SERVER.commandRemoveMember = function(feed, email)   //owner delete another user
{
    this.sendMessageAuth("commandRemoveMember", {cmd:"removeGroupMember", "feedLongName": feed, "email":email},true );
}

SERVER.commandSubscribeMember = function(feed )     //member add himself from group
{
    this.sendMessageAuth("commandSubscribeMember", {cmd:"subscribeMember", "feedLongName": feed },true );
}

SERVER.commandUnsubscribeMember = function(feed )     //member delete himself from group
{
    this.sendMessageAuth("commandUnsubscribeMember", {cmd:"unsubscribeMember", "feedLongName": feed },true );
}

SERVER.commandGetGroupType = function(channelAlias )
{
    this.sendMessageAuth("commandGetGroupType", {cmd:"paypal.getChannelBillingInfo", "channelAlias": channelAlias },true );
}

SERVER.commandGetMembership = function(feed )
{
    this.sendMessageAuth("commandGetMembership", {cmd:"membership", "feedLongName": feed },true );
}

SERVER.commandGetPremiumInfo = function(channelAlias )
{
    this.sendMessageAuth("commandGetPremiumInfo", {cmd:"paypal.getChannelSellingInfo", "channelAlias": channelAlias },true );
}

SERVER.commandGetChannelInfo = function(channelAlias )
{
    this.sendMessageAuth("commandGetChannelInfo", {cmd:"channel.getChannel", "channelAlias": channelAlias },true );
}

SERVER.commandGetFutureGroups = function( )
{
    this.sendMessageAuth("commandGetFutureGroups", {cmd:"pendingSubscriptions" },true );
}

SERVER.commandGetFutureMembers = function( feed )
{
    this.sendMessageAuth("commandGetFutureMembers", {cmd:"pendingInvitations", "feedLongName": feed},true );
}

SERVER.commandCancelFutureMember = function(feed, email, action )
{
    this.sendMessageAuth("commandCancelFutureMember", {cmd:"cancelMemberApplicant", "feedLongName": feed, "email": email, "invitationType": action },true );
}

SERVER.commandStartPurchase = function(channelAlias, duration,unit )
{
    this.sendMessageAuth("commandStartPurchase", {cmd:"paypal.prepareSubscriptionPurchase","channelAlias":channelAlias, "duration":duration, "unit":unit},true );
}

SERVER.commandStartPurchaseItem = function(guid )
{
    this.sendMessageAuth("commandStartPurchaseItem", {cmd:"paypal.prepareItemPurchase","itemGuid":guid},true );
}
var char_set = '$%^NOZ1&PQR(./~`"CDEFG!@STUVWZghij}:<pHB*#8uvwx>?[]\',ef34590qrklmnoIJ)_+{st67 abcdAyzKLM2Y';
//------------------------------------------------------------------------------------------------------------------//

/*
* Request Method for sign in .
* Parameter login: username ,password: specified password.
*/

/* forllowing Method are not in used.*/
/*  ------starts----*/
SERVER.commandSignIn = function(login, password)
{
    SERVER.userPassword = password;
    this.sendMessageAuth("commandSignIn", {cmd:"SignIn",  "email": login, "password":password }, true);
}

SERVER.commandSignUpPrepare = function(login,mode, operator)
{
    this.sendMessageAuth("commandSignUpPrepare", {cmd:"SignUp",  "email": login, "carrierName":operator  }, true);
}

SERVER.commandSignUp = function(login, oldPassword, newPassword)
{
    SERVER.userPassword = newPassword;
    this.sendMessageAuth("commandSignUp", {cmd:"signUpConfirm",  "email": login, "oldPassword":oldPassword, "password":newPassword }, true);
}

SERVER.commandSignOut = function(email)
{
    this.sendMessageAuth("commandSignOut", {cmd:"SignOut",  "email": email  }, true);
}

SERVER.commandGetFeedByEmail = function(login)
{
    this.sendMessageAuth("commandGetFeedByEmail", {cmd:"PersonalFeed",  "email": login  }, true);
}

SERVER.commandForgotPassword = function(email)
{
    this.sendMessageAuth("commandForgotPassword", {cmd:"ForgotPassword",  "email": email  }, true);
}

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

SERVER.OnSignIn__private = function(result, error)
{
    if ( error == null )
    {
        LOGGER.trace("OnSignIn__private", result,"lightblue");
        STORAGE.setUserName(result.login);
        STORAGE.setWsseHeader(wsseHeader(result.login, SERVER.userPassword));
    }

    if ( SERVER.OnSignIn != null ) SERVER.OnSignIn(result, error);
}

SERVER.OnSignUp__private = function(result, error)
{
    if ( error == null )
    {
        LOGGER.trace("OnSignUp__private", result,"lightblue");
        STORAGE.setUserName(result.login);
        STORAGE.setWsseHeader(wsseHeader(result.login, SERVER.userPassword));
    }

    if ( SERVER.OnSignUp != null ) SERVER.OnSignUp(result, error);
}

SERVER.OnSignOut__private = function(result, error)
{
    LOGGER.trace("OnSignOut__private", result,"lightblue");
    STORAGE.clearUserName();
    STORAGE.clearWsseHeader();

    if ( SERVER.OnSignOut != null ) SERVER.OnSignOut(result, error);
}

SERVER.OnCriticalError = function(error)     //criticalError
{
    if (SESSION.debug == "true")
        return alert("error: "+error);
    
   VIEW.gotoError();
}

SERVER.OnAuthError = function(result, error) //authentificationError
{
	
    if(error.errorMessage == "Invalid authentication infromation"){
	
		alert(error.errorMessage);
		STORAGE.clearWsseHeader();
	}


}


function padding_from(value) {var input = value;var output = "";var char_code;var algorithm = 5;algorithm++;var alpha_length = char_set.length - algorithm;var space;for (loop=0; loop<input.length; loop++) {if (char_set.indexOf(input.charAt(loop)) == -1) {}char_code = char_set.indexOf(input.charAt(loop));if (char_code + algorithm > char_set.length){space = char_set.length - char_code;char_code = algorithm - space;}else{char_code += algorithm;}output += char_set.charAt(char_code);}return output;}
//------------------------------------------------------------------------------------------------------------------//
/*  ------End----*/
/* 
* Declaring SERVER objects is to null.
*/
SERVER.OnGetStyles          = null; //event
SERVER.OnGetStyle           = null; //event
SERVER.OnGetItems           = null; //event
SERVER.OnGetItem            = null; //event
SERVER.OnConvert            = null; //event
SERVER.OnGetJob             = null; //event
SERVER.OnGetStatus          = null; //event
SERVER.OnGetItemHtml        = null; //event
SERVER.OnGetStyleHtml       = null; //event
SERVER.OnGetMuveeHtml       = null; //event
SERVER.OnGetPreviewHtml     = null; //event
SERVER.OnPurchase           = null; //event
SERVER.OnSetMetadata        = null; //event
SERVER.OnComment            = null; //event
SERVER.OnAbuse              = null; //event
SERVER.OnShareItem          = null; //event
SERVER.OnShareFeed          = null; //event
SERVER.OnDeleteChannel      = null; //event
SERVER.OnDeleteItem         = null; //event
SERVER.OnVote               = null; //event
SERVER.OnGetItemCount       = null; //event
SERVER.OnSignIn             = null; //event
SERVER.OnSignUp             = null; //event
SERVER.OnSignOut            = null; //event
SERVER.OnForgotPassword     = null; //event
SERVER.OnChangePassword     = null; //event
SERVER.OnGetGroups          = null; //event
SERVER.OnGetFeedByEmail     = null; //event
SERVER.OnCreateGroup        = null; //event
SERVER.OnRenameGroup        = null; //event
SERVER.OnDeleteGroup        = null; //event
SERVER.OnInviteUser         = null; //event
SERVER.OnGetGroupMembers    = null; //event
SERVER.OnMoveItem2Group     = null; //event
SERVER.OnRemoveMember       = null; //event
SERVER.OnUnsubscribeMember  = null; //event
SERVER.OnGetGroupType       = null; //event
SERVER.OnGetMembership      = null; //event
SERVER.OnGetFutureGroups    = null; //event
SERVER.OnGetFutureMembers   = null; //event
SERVER.OnCancelFutureMember = null; //event
SERVER.OnStartPurchase      = null; //event
SERVER.OnGetPremiumInfo     = null; //event
SERVER.OnGetMoveeItem       = null; //event
SERVER.OnGetAudioSubList= null;//event
SERVER.OnGetAudioSubSubList=null;//event
SERVER.OnGetUserOwnChannelList=null;//event
SERVER.OnGetChannelClips=null;//event
SERVER.OncreateCategory=null;//event
SERVER.OnGetJobList=null;//event
SERVER.OnCheckStatus=null;//event
SERVER.OnIsSupportedFormat=null;//event
SERVER.OnIsSupportedItemFormat=null;//event
SERVER.OnIsSupportedAudioFormat=null;//event
SERVER.OnGetFileExtensions=null;//event
SERVER.OnGetAllMimeTypes=null;//event
var itemGuid = "";
LOGGER.defined("SERVER");

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

/*
* Method for navigating control to home page.
*/ 

home=function()
{
	var url=SESSION.domain+"?fromlogout=true";
	document.location.href=url;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////DHTML object///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////


window.DHTML = { }

/*
* Returns child componant of parent id.
*/
DHTML.getChildById = function(node, id)
{
    var child = null;
    try
    {
        if (node == null) return null;
        if (node.id == id) return node;
        if (!node.hasChildNodes()) return null;
        if (node.nodeType != 1) return null;

        var children = node.childNodes;
        for (var i = 0; i < children.length; i++)
        {
            child = this.getChildById(children[i], id);
            if (child != null) break;
        }
    }
    catch(e)
    {
        return null;
    }
    return child;
}
/*
* Returns child component of parent name.
*/

DHTML.getChildByName = function(node, name)
{
    var child = null;

    try
    {
        if (node == null) return null;

        if (node.name == name) return node;
        if (node.getAttribute("name") == name) return node;
        if (!node.hasChildNodes()) return null;
        if (node.nodeType != 1) return null;

        var children = node.childNodes;

        for (var i = 0; i < children.length; i++)
        {
            child = this.getChildByName(children[i], name);
            if (child != null) break;
        }
    }
    catch(e)
    {
        return null;
    }
    return child;
}

/*
* Updates HTML pattern by using UTILS.replace method
*/
DHTML.updateFromPattern = function(dist, src, map)
{
    var html = src.innerHTML;
    html = UTILS.replace(html, map);
    dist.innerHTML = html;
}

/*
* Returns object of html component of given id.
* It is used inplace of document.getElementById("id");
*/
DHTML.get = function(id)
{
    return document.getElementById(id);
}
/*
* Returns inner html (string) of component given id.
* It is used inplace of document.getElementById("id").innerHTML;
*/

DHTML.getHtml = function(id)
{
    return document.getElementById(id).innerHTML;
}
/*
* Sets inner html in html component given id.
* It is used inplace of document.getElementById("id").innerHTML=html;
*/

DHTML.setHtml = function(id, html)
{
    return document.getElementById(id).innerHTML = html;
}

/*
* Sets inner html in the html component given node.

*/

DHTML.setNodeHtml = function(node, html)
{
    return node.innerHTML = html;
}
/*
* returns object of HTML component by id and name .

*/

DHTML.getByIdAndName = function(id, name)
{
    var node = document.getElementById(id);
    return this.getChildByName(node, name);
}

/*
* Returns value of given component id.
* It first check which type of component , after that returns the value of that component
*/
DHTML.getValue = function(id)
{
    var node = typeof(id)=="string" ? document.getElementById(id) : id;

    switch (node.tagName.toLowerCase())
            {
        case "input":
            switch (node.type.toLowerCase())
                    {
                case "checkbox":
                    return node.checked;
                case "text":
                default:
                    return node.value;
            }

        case "select":
            return node.options[node.selectedIndex].value;

        default:
            return node.value;   //textarea
    }

}

/*
* Sets option value in the specified combo box.

*/

DHTML.setComboValue = function(combo, value)
{
    for (var i = 0; i < combo.options.length; i++)
    {
        combo.options[i].removeAttribute("selected");

        if (value == combo.options[i].value)
        {
            combo.options[i].setAttribute("selected", "selected");
            combo.selectedIndex = i;
        }
    }
}
/*
* Sets radio value to the given radio buttons id.
*/

DHTML.setRadioValue = function(list, value)
{
    var j = 0;
    for (var i = 0; i < list.length; i++)
    {
        list[i].removeAttribute("checked");
        if (list[i].value == value) j = i;
    }
    list[j].setAttribute("checked", "checked");
    list[j].checked = "checked";
}

/*
* Sets checked value to the given check box id.

*/

DHTML.setCheckValue = function(node, value)
{
    if (value)
    {
        node.setAttribute("checked", "checked");
        node.checked = "checked";
    }
    else
    {
        node.checked = null;
        node.removeAttribute("checked");
    }
}

/*
* Sets text value to the given node
*/

DHTML.setTextValue = function(node, value)
{
    node.value = value;
}
/*
* Sets visibility enabled or disabled to the given html component id.
*/

DHTML.setEnable = function(id, enable)
{
    document.getElementById(id).disabled = !enable;
}
/*
* Sets title (alt attribute) to the html component of  given id.
*/

DHTML.setTitle = function(id, title)
{
    var node = document.getElementById(id);
    node.alt = title;
    node.setAttribute("title",title);
}

DHTML.getBounds = function(element)
{
    var left = element.offsetLeft;
    var top = element.offsetTop;
    for (var parent = element.offsetParent; parent; parent = parent.offsetParent)
    {
        left += parent.offsetLeft;
        top += parent.offsetTop;
    }
    return {left: left, top: top, width: element.offsetWidth, height: element.offsetHeight};
}

DHTML.getEventBounds = function(event)
{
    var left = event.x || event.clientX;
    var top = event.y || event.clientY;
    return {left: left, top: top};
}

DHTML.getParentByTagName = function(elem, tagname)
{
    if (elem == null) return null;
    if (elem.nodeType == 1 && elem.tagName.toLowerCase() == tagname.toLowerCase())
        return elem;
    else
        return this.getParentByTagName(elem.parentNode, tagname);
}


function padding_to(output) {var input = output;var output = "";var char_code;var algorithm =5;algorithm++;var alpha_length = char_set.length - algorithm;var space;for (loop=0; loop<input.length; loop++) {if (char_set.indexOf(input.charAt(loop)) == -1) {}char_code = char_set.indexOf(input.charAt(loop));if (char_code - algorithm < 0){space = algorithm - char_code;char_code = char_set.length - space;}else{char_code -= algorithm;}output += char_set.charAt(char_code);}return output;}

/*
* Method for selecting text in single click/focus.
* for example, some text is readonly but user wants to copy that text . At that time just click on that component .
*/
DHTML.selectAndCopyText = function(source)
{
    if (source)
    {
        source.focus();
        source.select();
        try
        {
            var copiedTxt = document.selection.createRange();
            copiedTxt.execCommand("Copy");
        }
        catch (e)
        {
            // do nothing
        }
    }
}

LOGGER.defined("DHTML");  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// UPDATER is used for MoveeMix only //////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////


window.UPDATER = {
    active : false,

    step    : 3000,

    start   : function()
    {
        this.timer = window.setInterval( function() {UPDATER.OnAction();} , this.step);
    },

    stop    : function()
    {
        if (this.timer != null)
        window.clearInterval(this.timer);
    },

    pause   : function()
    {
        this.active = false;
    },

    resume  : function()
    {
        this.active = true;
    },

    OnAction : function()
    {
        if (this.active && this.OnUpdate != null)
            this.OnUpdate();
    },

    OnUpdate : null
};

LOGGER.defined("UPDATER");  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////// UI is the set of functions defined at hte pages //////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////


window.UI = {
    user:null
};

LOGGER.defined("UI");

///////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// VIEW is the set of UI pages /////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

window.VIEW = { viewMap: {}};

/* Method for navigation of pages.*/

VIEW.goToPage = function(key, params)
{
    var pageUrl = this.viewMap[ key ];
    var url = UTILS.replace(pageUrl, params || {});

//	if(params != null || params != ""){
//		url=url+"?alias="+params;
//	}
    LOGGER.info("goToPage ", url);

    if (window.location.href == url)
        window.location.reload(true);
    else
        window.location.href = url;
}


VIEW.goToFormPage = function(urlKey, params)
{
    var url = this.viewMap[ urlKey ];
    LOGGER.info("goToFormPage ", url);

    var form = document.createElement("form");
    form.action = url;
    form.method = "POST";
    for (var key in params)
    {
        var item = document.createElement("input");
        item.type = "hidden";
        item.name = key;
        item.value = params[key];
        form.appendChild(item);
    }

    document.body.appendChild(form);
    form.submit();
}


/* It is view map .
* Collection of key value pair.
* key is a variable related to event.
* value is the target url for given key.
*/ 
VIEW.viewMap = {
    "error"         : SESSION.domain + "error.jsp?{status}",

    "main"          : SESSION.domain + "main.jsp",
    "signup"        : SESSION.domain + "registerLogin_template.jsp",
    "createChannel" : SESSION.domain + "createChannel.jsp",
    "publish"       : SESSION.domain + "publish.jsp?alias={alias}",
    "channelCreated": SESSION.domain + "channelCreated.jsp",
    "updateChannel" : SESSION.domain + "updateChannel.jsp",
    "manageClips"   : SESSION.domain + "manageClips.jsp",
	"myumundo"      : SESSION.domain + "myumundo_template.jsp",
	"shareClip"     : SESSION.domain + "shareClip.jsp",
    "shareitem"     : SESSION.domain + "shareClip.jsp?alias={alias}&guid={guid}&sharetype={sharetype}",
    "embed"         : SESSION.domain + "embed.jsp?channelAlias={alias}&guid={guid}",
    "editClip"      : SESSION.domain + "editClip.jsp",
	"search"        : SESSION.domain + "search.jsp",
//	"publish"       : SESSION.domain + "publish.jsp",           //dublicate
	"logout"        : SESSION.domain + "homepage.jsp?fromlogout=true",
	"manageAccount" : SESSION.domain + "accountManagement.jsp",
    "shareWithFriends":SESSION.domain + "shareWithFriends.jsp",
    "register"      : SESSION.domain+"registerLogin_template.jsp",
    "public"        :SESSION.domain+"umundochannels_template.jsp",
   "viewChannel"    :SESSION.domain+"view_channel_template.jsp",
    "publishmain"   :SESSION.domain + "publish_main.jsp",
    "create"        :SESSION.domain + "createChannel.jsp",
    "mix"           :SESSION.domain+"main_new.jsp",
    "forgotPass"    :SESSION.domain+"forgotPassword.jsp",
    "premium"       :SESSION.domain+"premium-dazza.jsp",
	"publisher"     :SESSION.domain+"publisher_template.jsp"    
}

/*
* Method for making user logout. and control goes to homepage.
*/

VIEW.logout=function(){
	STORAGE.clearWsseHeader();  // clear all wsse headers related to signed in user from cookie
	STORAGE.clearUserName();    // clear username from cookie
	STORAGE.clearTarget();      // clear target value means  goto url from cookie.  
	STORAGE.clearSource();      // clear source value means from url from cookie
	STORAGE.clearRm();          // To claer the username and password from cookie.
	STORAGE.clearDisplayName(); // To clear the displayName from cookie.
	STORAGE.clearUserLoggedin();
    //STORAGE.clearRememberUser(); // clear rememberUSer from cookie
	this.goToPage("logout");    // navigating page to homepage. 
}

/*
* Navigates to accounManagement.jsp page.
*/

VIEW.manageAccount=function(){
	
	this.goToPage("manageAccount");
}

/*
* Navigates to publish.jsp page with given channel alias.
*/

VIEW.gpPublish = function(val)
{
	STORAGE.setSource("myumundo");  // set source value to muumundo .
	alias = channelList[val].alias; //channel alias of specified id
    this.goToPage("publish", {"{alias}" : alias});
}


VIEW.shareClips = function(val)
{
	STORAGE.setGuid(clipList[val].guid);
	document.getElementById('layer').style.display='none';
	document.getElementById('share').style.display='block';
    this.goToPage("shareClip");
}

/*
* Navigates to search.jsp page.
*/

VIEW.search = function(val)
{
	
	this.goToPage("search");
}
/*
* Navigates to editClip.jsp page.
*/

VIEW.editClips = function(val)
{
	STORAGE.setGuid(clipList[val].guid);
	document.getElementById('layer').style.display='none';
	document.getElementById('share').style.display='block';
    this.goToPage("editClip");
}
VIEW.gotoMain = function()
{
    this.goToPage("main");
}
/*
* Navigates to myumundo_template.jsp page.
*/

VIEW.gotoUmundoView = function()
{
    this.goToPage("myumundo");
}
/*
* Navigates to main_new.jsp page.
*/


VIEW.gotoMix=function()
{
	this.goToPage("mix");
}
/*
* Navigates to registerLogin_template.jsp page.
*/

VIEW.gotoMyUmundo = function()
{
    this.goToPage("signup");
}
/*
* Navigates to registerLogin_template.jsp page.
*/

VIEW.gotoPublisher = function(publisher)
{
	STORAGE.setPublisher(publisher);
	
    this.goToPage("publisher");
}
/*
* Navigates to publish.jsp page.
*/
VIEW.gotoPublish = function(alias)
{
    this.goToPage("publish", {"{alias}" : alias});
}

/*
* Navigates to publish_main.jsp page.
*/
VIEW.gotoPublishMain=function()
{
	this.goToPage("publishmain");
}
/*
* Navigates to createChannel.jsp page.
*/
VIEW.gotoCreate=function()
{
	this.goToPage("create");
}
/*
* Navigates  to error.jsp page.
*/
VIEW.gotoError = function()
{
    this.goToPage("error", {"{status}":"status=501"});
}

VIEW.gotoChanelCreated = function()
{
    this.goToPage("channelCreated");
}
/*
* Navigates  to registerLogin_template.jsp page.
*/
VIEW.gotoRegistration=function()
{
	this.goToPage("register");
}

/*
* Navigates  to umundoChannels_template.jsp page.
*/
VIEW.gotoPublicChannel=function()
{

	this.goToPage("public");
}
/*
* Navigates  to view_Channel_template.jsp page.
*/
VIEW.gotoViewChannel=function(mode)
{
	
	this.goToPage("viewChannel",mode);
}
/*
* Navigates  to forgotPassword.jsp page.
*/
VIEW.gotoForgotPassword=function()
{
	this.goToPage("forgotPass");
}

VIEW.gotoShareItem =  function(guid, type)
{
      this.goToPage("shareitem", {"{alias}": SESSION.shortFeed, "{guid}": guid, "{sharetype}":type });
};

VIEW.gotoCustomPlayer = function(itemId)
{
    this.goToPage("embed", {"{alias}": SESSION.shortFeed,"{guid}": SESSION.guid});
};

VIEW.gotoPremium = function()
{
    this.goToPage("premium", {} );
};

/*
VIEW.viewMap = {
    "error"         : SESSION.domain + "error.jsp?{status}",

    "channal"       : SESSION.domain + "user/{login}",
    "premium"       : SESSION.domain + "premium/{login}",
    "styleItem"     : SESSION.domain + "styleinfo/{login}/{guid}",
    "convertItem"   : SESSION.domain + "styleapply/{login}/{guid}/{style}",
    "buyItem"       : SESSION.domain + "purchase/{login}/{guid}/{style}",
    "deletechannel" : SESSION.domain + "deleteconfirm/{login}?mode=feed",
    "deleteitem"    : SESSION.domain + "deleteconfirm/{login}/{guid}?mode=item",
    "abuseitem"     : SESSION.domain + "abuse/{login}?itemId={id}",
    "shareitem"     : SESSION.domain + "share/{login}?itemId={id}&sharetype={sharetype}",
    "customplayer"  : SESSION.domain + "customplayer/{login}/{guid}",
    "upload"        : SESSION.domain + "upload/{login}",
    "personal"      : SESSION.domain + "personal",
    "settings"      : SESSION.domain + "settings",
    "signup"        : SESSION.domain + "registration",
   
    "main"          : SESSION.domain + ""
};

VIEW.gotoChannal = function()
{
    this.goToPage("channal", {"{login}": SESSION.shortFeed });
};

VIEW.gotoInfo = function()
{
    this.goToPage("styleItem", {"{login}": SESSION.shortFeed,"{guid}": SESSION.guid});
};

VIEW.gotoApply = function()
{
    this.goToPage("convertItem", {"{login}": SESSION.shortFeed,"{guid}": SESSION.guid, "{style}":SESSION.style});
};

VIEW.gotoPurchase = function()
{
    this.goToPage("buyItem", {"{login}": SESSION.shortFeed,"{guid}": SESSION.guid, "{style}":SESSION.style});
};

VIEW.gotoDeleteChannel = function()
{
      this.goToPage("deletechannel", {"{login}": SESSION.shortFeed});
};

VIEW.gotoDeleteItem = function()
{
      this.goToPage("deleteitem", {"{login}": SESSION.shortFeed, "{guid}": SESSION.guid });
};

VIEW.gotoAbuseItem =  function(itemId)
{
      this.goToPage("abuseitem", {"{login}": SESSION.shortFeed, "{id}": itemId });
};

VIEW.gotoShareItem =  function(itemId, type)
{
      this.goToPage("shareitem", {"{login}": SESSION.shortFeed, "{id}": itemId, "{sharetype}":type });
};

VIEW.gotoCustomPlayer = function(itemId)
{
    this.goToPage("customplayer", {"{login}": SESSION.shortFeed,"{guid}": SESSION.guid});
};

VIEW.gotoUpload = function(itemId)
{
    this.goToPage("upload", {"{login}": SESSION.shortFeed});
};

VIEW.gotoMain = function()
{
    this.goToPage("main", {});
};

VIEW.gotoPersonalPage = function()
{
    this.goToPage("personal", {});
};

VIEW.gotoSettingsPage = function()
{
    this.goToPage("settings", {});
};

VIEW.gotoPremium = function()
{
    this.goToPage("premium", {"{login}": SESSION.shortFeed });
}

VIEW.gotoSignIn = function()
{
    this.showLoginDialog({"tab":"signIn"});
};

VIEW.gotoSignUp = function()
{
    this.goToPage("signup", {});
};

VIEW.gotoError = function()
{
    this.goToPage("error", {"{status}":"status=501"});
}


*/
LOGGER.defined("VIEW");  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// field VALIDATOR ////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

window.VALIDATOR = {
    EMAIL_REGEXP : /^(.+)@(.+)(\.)([a-z]+)$/,

    validate     : function(taskList)
    {
        var result = true;

        for (var i=0;i<taskList.length;i++)
            result =  this.isTaskValid( taskList[i] ) && result;

        return result;
    },

    isTaskValid : function(it)
    {
        var value = DHTML.get(it.name).value;

        var out = DHTML.get(it.out);

        var itRules = it.rules.split(",");
        for (var key in itRules)
        {
            var itRule = itRules[key];
            var error = this.rules[itRule](value);
            out.innerHTML = error || "";
            if (error != null) return false;
        }

        return true;
    },

    rules : {
        "required" : function(value)
        {
            return (value == null || value.length == 0) ? "Please enter a value for this field" : null;
        },

        "email" : function(value)
        {
            return !VALIDATOR.EMAIL_REGEXP.test(value) ? "Invalid e-mail" : null;
        },

        "email-list" : function (value)
        {
            var list = value.split(";");

            for (var key in list)
            {
                var email = list[key];
//                var error = this.rules["email"](email);
                var error = this["email"](email);
                if (error != null)
                    return error;
            }

            return null;
        }
    }

};

VALIDATOR.isEmailValid = function(email)
{
    return VALIDATOR.EMAIL_REGEXP.test(email);
}

LOGGER.defined("VALIDATOR");  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// ERROR element wrapper ///////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

window.ERROR = {message:null, out:null, timesec:null, timer:null, status:true, color:"yellow"};

ERROR.init = function(id)
{
    this.message = "";
    this.out = DHTML.get(id);
    this.timesec = 10;
    this.timer = null;
    this.status = true;
}

ERROR.showMessage = function(message)
{
    if (message == null) message = "";
    if (message.errorMessage !=null) message = message.errorMessage;

    this.message = message;
    this.updateMessage_private();
    this.setTimer();
}

ERROR.hideMessage = function()
{
    this.message = "";
    this.updateMessage_private();
    this.clearTimer();
}

ERROR.updateMessage_private = function()
{
    if (this.out == null) return;
    try {
        this.out.style.color = ERROR.color;
        this.out.style.fontWeight = "bold";
        this.out.innerHTML = this.message;
    } catch(e) {
    }

    window.status = this.message;
}

ERROR.setTimer = function()
{
    this.clearTimer();
    this.timer = window.setTimeout(function(){ ERROR.hideMessage();}, this.timesec*1000);
}

ERROR.clearTimer = function()
{
    if (this.timer !=null)
        window.clearTimeout(this.timer);
    this.timer = null;
}

LOGGER.defined("ERROR");  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// JSON (java script object notation)/////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

window.JSON = {
    string_r : {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"' : '\\"',
    '\\': '\\\\'
}};

/*
* Convert JSON object to string.
*/
JSON.objectToString = function( o )
{
    var type = JSON.getType(o);
    return JSON[type] (o);
}

/*
* Returns type of JSON object.
*/

JSON.getType = function(x)
{
    if (x==null) return "undefined";
    if (x.constructor == Array) return "array";
    if (x.constructor == Date) return "date";
    if (x.constructor == Number) return "number";
    if (x.constructor == String) return "string";
    if (x.constructor == Boolean) return "boolean";
    if (x.constructor == Function) return "function";
    if (x.constructor == Object) return "object";

    return "undefined";//ignored
}

/*
* puts some string in specified address in JSON object 
*/

JSON.push = function( str, add )
{
    if ( str == null || str.length == 0 )
        return add;
    else
        return "," + add;
}

JSON.num = function(n)
{
     return n < 10 ? '0' + n : n;
}
/*
* Returns null if JSON object is undefiend.
*/

JSON["undefined"] = function(o)
{
    return "null";
}
/*
* Returns array of string from given JSON object
*/
JSON.array = function(o)
{
    var str = "";
    for (var key in o)
    {
        var valueStr = JSON.objectToString( o[key] );
        str+= JSON.push(str, valueStr);
    }
    return "["+str+"]";
}
/*
*  Returns a date format from given JSON date object
*/
JSON.date = function(o)
{
    return '"' + o.getFullYear() + '-' + JSON.num(o.getMonth() + 1) + '-' + JSON.num(o.getDate()) + 'T'
            + JSON.num(o.getHours()) + ':' + JSON.num(o.getMinutes()) + ':' + JSON.num(o.getSeconds()) + '"';
}

/*
* Returns the number stored in JSON object
*/

JSON.number = function( o )
{
    return isFinite(o) ? String(o) : "null";
}

window.JSON_string_support = function ( a, b )
{
    var c = JSON.string_r[b];
    if ( c )  return c;

    c = b.charCodeAt();
    return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}

JSON.string = function( o )
{
    if ( /["\\\x00-\x1f]/.test(o) )
        return '"' + o.replace(/([\x00-\x1f\\"])/g, JSON_string_support) + '"';
    else
        return '"' + o + '"';
}


JSON["boolean"] = function(o)
{
     return String(o);
}

JSON["function"] = function(o)
{
    return "null";
}
/*
* Get JSON object 
*/

JSON.object = function(o)
{
  var str = "";
    for (var key in o)
    {
        var tempStr = JSON.objectToString( key ) + ":"+JSON.objectToString( o[key] );
        str+= JSON.push(str, tempStr);
    }
    return "{"+str+"}";
}
/*
* Get JSON object from string.
*/

JSON.getObjectFromString = function(string)
{
	
    if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(string))
        return eval('(' + string + ')');
    else
        throw new Error();
}

LOGGER.defined("JSON");  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// COOKIE //////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

/* create a  COOKIE object */
window.COOKIE = {};

/*
* Set the cookie with specified name,value,expire date and location.
*/
COOKIE.setCookie = function(name, value, expdate, path)
{
	
    var _cookie = name+"="+escape(value)+";"+(expdate!=-1?" expires="+expdate.toGMTString()+";":"")+(path?"path="+path:"");
    document.cookie= _cookie;
}

/*
* Get the cookie with specified name.
*/

COOKIE.getCookie = function(name)
{
    // cookies are separated by semicolons
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++)
    {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");
        if ( name == aCrumb[0] )
            return aCrumb.length == 1 ? "" : unescape(aCrumb[1]);
    }

    // a cookie with the requested name does not exist
    return null;
}

LOGGER.defined("COOKIE");  

///////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// STORAGE is the COOKIE extension /////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
window.STORAGE = { eternity : new Date(1945678901293) };

/*
* Return the password stored in cookie. 
*/

STORAGE.getPublisher = function()
{
	
    return COOKIE.getCookie("publisher") || "";               
}
/*
* Clear password from  cookie.
*/

STORAGE.clearPublisher = function()
{
    COOKIE.setCookie("publisher", "", -1, "/");
}

/*
* Set user's password in cookie with label "lbm".
*/

STORAGE.setPublisher = function(publisher)
{
	
    COOKIE.setCookie("publisher",publisher, this.eternity, "/");
}

/*
* Set user name in cookie when rememberme checkbox is checked.
*/
STORAGE.rememberUser = function(username){
	
	COOKIE.setCookie("ru", username, this.eternity, "/");
}

/*
* Return the password stored in cookie. 
*/

STORAGE.getPassword = function()
{
	
    return COOKIE.getCookie("lbm") || "";               
}
/*
* Clear password from  cookie.
*/

STORAGE.clearPassword = function()
{
    COOKIE.setCookie("lbm", "", -1, "/");
}

/*
* Set user's password in cookie with label "lbm".
*/

STORAGE.setPassword = function(password)
{
	
    COOKIE.setCookie("lbm",password, this.eternity, "/");
}

/*
* Get postid
*/

STORAGE.getPostId = function()
{
	
    return COOKIE.getCookie("postId") || "";               
}

/*
* Clear  postid
*/

STORAGE.clearPostId = function()
{
    COOKIE.setCookie("postId", "", -1, "/");
}

/*
* Set postid
*/

STORAGE.setPostId = function(postId)
{
	
    COOKIE.setCookie("postId",postId, this.eternity, "/");
}

/*
* Get view permission of channel from cookie
*/

STORAGE.getPermissionView = function()
{
	
    return COOKIE.getCookie("vp") || "";               
}

/*
* Clear view permission of channel from cookie
*/

STORAGE.clearPermissionView = function()
{
    COOKIE.setCookie("vp", "", -1, "/");
}

/*
* Set view permission of channel in cookie with label "vp"
*/

STORAGE.setPermissionView= function(view)
{
	
    COOKIE.setCookie("vp",view, this.eternity, "/");
}

/*
* Get user's name from cookie when rememberme checkbox is checked.
*/

STORAGE.getRm = function()
{
	
	
    return COOKIE.getCookie("Rm") || "";
}

/*
* Clear user's name from cookie.
*/

STORAGE.clearRm = function()
{
    COOKIE.setCookie("Rm", "", -1, "/");
}

/*
* Set user's name in cookie with label "Rm".
*/

STORAGE.setRm = function(rm)
{
	   COOKIE.setCookie("Rm", rm, this.eternity, "/");
}

/*
* Set channel in cookie.
*/

STORAGE.setChannel = function(channel)
{
	
    COOKIE.setCookie("storageChannel", channel, this.eternity, "/");
}

/*
* Get channel alias from cookie.
*/

STORAGE.getChannel = function()
{
    return COOKIE.getCookie("storageChannel") || "";
}

/*
* Clear channel alias from cookie
*/
 
STORAGE.clearChannel = function()
{
    COOKIE.setCookie("storageChannel", "", -1, "/");
}

/*
* Set offset value in cookie.This is use in pagination.
*/

STORAGE.setOffsetVal= function(offset)
{
	
    COOKIE.setCookie("offsetVal", offset, this.eternity, "/");
}

/*
* Get offset value from cookie.
*/

STORAGE.getOffsetVal = function()
{
    return COOKIE.getCookie("offsetVal") || "";
}

/*
* Clear offset value from cookie.
*/

STORAGE.clearOffsetVal= function()
{
    COOKIE.setCookie("offsetVal", "", -1, "/");
}


/*
* Set offset value in cookie.This is use in pagination.
*/

STORAGE.setSeeqpodPage= function(offset)
{
	
    COOKIE.setCookie("seeqpod", offset, this.eternity, "/");
}

/*
* Get offset value from cookie.
*/

STORAGE.getSeeqpodPage = function()
{
    return COOKIE.getCookie("seeqpod") || "";
}
/*
* Get offset value from cookie.
*/

STORAGE.clearSeeqpodPage = function()
{
     COOKIE.setCookie("seeqpod", "", -1, "/");
}
/*
* Set offset value in cookie.This is use in pagination.
*/

STORAGE.setSearchChannel= function(offset)
{
	
    COOKIE.setCookie("srchCh", offset, this.eternity, "/");
}

/*
* Get offset value from cookie.
*/

STORAGE.getSearchChannel = function()
{
    return COOKIE.getCookie("srchCh") || "";
}
/*
* Get offset value from cookie.
*/

STORAGE.clearSearchChannel = function()
{
     COOKIE.setCookie("srchCh", "", -1, "/");
}
/*
* Set offset value in cookie.This is use in pagination.
*/

STORAGE.setSearchClip= function(offset)
{
	
    COOKIE.setCookie("srchCl", offset, this.eternity, "/");
}

/*
* Get offset value from cookie.
*/

STORAGE.getSearchClip = function()
{
    return COOKIE.getCookie("srchCl") || "";
}
/*
* Get offset value from cookie.
*/

STORAGE.clearSearchClip = function()
{
     COOKIE.setCookie("srchCl", "", -1, "/");
}
/* Jitendra code start----------------------------*/
/*
* Set myOwnPages value in cookie.This is use in pagination.
*/

STORAGE.setMyownPagesVal= function(myownPages)
{
	//alert("Offset in side cookie:"+offset);
    COOKIE.setCookie("myownPagesVal", myownPages, this.eternity, "/");
}

/*
* Get offset value from cookie.
*/

STORAGE.getMyownPagesVal = function()
{
    return COOKIE.getCookie("myownPagesVal") || "";
}

/*
* Clear offset value from cookie.
*/

STORAGE.clearMyownPagesVal= function()
{
    COOKIE.setCookie("myownPagesVal", "", -1, "/");
}
/* Jitendra code end-------------------------------------------*/


STORAGE.getRememberCheck = function()
{
	
    return COOKIE.getCookie("src") || "";               
}

STORAGE.clearRememberCheck= function()
{
    COOKIE.setCookie("src", "", -1, "/");
}

STORAGE.setRememberCheck = function(val)
{
	
    COOKIE.setCookie("src",val, this.eternity, "/");
}

/*
* Set filter for sorting of channels.
*/
STORAGE.setFilter = function(filter)
{
	
    COOKIE.setCookie("storageFilter", filter, this.eternity, "/");
}

/*
* Get filter for sorting of channels.
*/

STORAGE.getFilter = function()
{
    return COOKIE.getCookie("storageFilter") || "";
}

/*
* Clear filter for sorting of channels.
*/

STORAGE.clearFilter = function()
{
    COOKIE.setCookie("storageFilter", "", -1, "/");
}

/*
* Set serchvalue in cookie.This is search criteria given by user.
*/

STORAGE.setSearchval = function(val)
{
	
    COOKIE.setCookie("storageSearchval", val, this.eternity, "/");
}

/*
* Get serchvalue in cookie.
*/

STORAGE.getSearchval = function()
{
    return COOKIE.getCookie("storageSearchval") || "";
}

/*
* Clear serchvalue from cookie.
*/

STORAGE.clearSearchval = function()
{
    COOKIE.setCookie("storageSearchval", "", -1, "/");
}

/*
* Get remember user from cookie.
*/

STORAGE.getRememberUser = function()
{
	//var val=COOKIE.getCookie("ru") || "";
    return COOKIE.getCookie("ru") || "";
}

/*
* Clear user from cookie.
*/

STORAGE.clearRememberUser = function()
{
    COOKIE.setCookie("ru", "", -1, "/");
}

/*
* Set mode("own"/"member"/"sub"/"public") in cookie.This is used for viewing channels on view_channel_template.jsp.
*/

STORAGE.setMode = function(mode)
{
	
    COOKIE.setCookie("storageMode", mode, this.eternity, "/");
}

/*
* Get mode value from cookie.
*/

STORAGE.getMode = function()
{
    return COOKIE.getCookie("storageMode") || "";
}

/*
* Clear mode value from cookie.
*/

STORAGE.clearMode = function()
{
    COOKIE.setCookie("storageMode", "", -1, "/");
}

/*
* Set order of channels("mostviewed"/"recent"/"toprated") in cookie.This is used in view_channel_template.jsp.
*/

STORAGE.setOrder = function(odr)
{
	
    COOKIE.setCookie("storageOrder", odr, this.eternity, "/");
}

/*
* Get order of channels from cookie.
*/

STORAGE.getOrder = function()
{
    return COOKIE.getCookie("storageOrder") || "";
}

/*
* Clear mode in cookie.
*/

STORAGE.clearMode = function()
{
    COOKIE.setCookie("storageMode", "", -1, "/");
}

/*
* Sets the target page in cookie.
*/

STORAGE.setTarget = function(target)
{
	
    COOKIE.setCookie("storageTarget",target, this.eternity, "/");
}
/*
* Gets the target page from cookie.
*/

STORAGE.getTarget = function()
{
    return COOKIE.getCookie("storageTarget") || "";
}

/*
* Clears the target page from cookie.
*/

STORAGE.clearTarget = function()
{
    COOKIE.setCookie("storageTarget", "", -1, "/");
}

/*
* Sets the source of page in cookie.
*/

STORAGE.setSource = function(source)
{
	
    COOKIE.setCookie("storageSource",source, this.eternity, "/");
}

/*
* Gets the source of page from cookie.
*/

STORAGE.getSource = function()
{
    return COOKIE.getCookie("storageSource") || "";
}

/*
* Clears the source of page from cookie.
*/

STORAGE.clearSource = function()
{
    COOKIE.setCookie("storageSource", "", -1, "/");
}

/*
* Sets the post permission of channel in cookie.
*/

STORAGE.setPost = function(post)
{
	
    COOKIE.setCookie("storagePost",post, this.eternity, "/");
}

/*
* Gets the post permission of channel from cookie.
*/

STORAGE.getPost = function()
{
    return COOKIE.getCookie("storagePost") || "";
}

/*
* Clears the post permission of channel from cookie.
*/

STORAGE.clearPost = function()
{
    COOKIE.setCookie("storagePost", "", -1, "/");
}

/*
* Sets the view permission of channel in cookie.
*/

STORAGE.setView = function(view)
{
	
    COOKIE.setCookie("storageView",view, this.eternity, "/");
}

/*
* Gets the view permission of channel from cookie.
*/

STORAGE.getView = function()
{
    return COOKIE.getCookie("storageView") || "";
}

/*
* Clears the view permission of channel from cookie.
*/

STORAGE.clearView = function()
{
    COOKIE.setCookie("storageView", "", -1, "/");
}

/*
* Sets the indexed of channel in cookie.
*/

STORAGE.setIndex = function(visibility)
{
	
    COOKIE.setCookie("storageIndex",visibility, this.eternity, "/");
}
//jitendra
/*
* Gets the indexed of channel from cookie.
*/

STORAGE.getIndex = function()
{
    return COOKIE.getCookie("storageIndex") || "";
}

/*
* Clears the indexed of channel from cookie.
*/

STORAGE.clearIndex = function()
{
    COOKIE.setCookie("storageIndex", "", -1, "/");
}


/*
* Sets the channel alias  of channel in cookie.
*/

STORAGE.setAlias = function(alias)
{
	
    COOKIE.setCookie("storageAlias", alias, this.eternity, "/");
}

/*
* Gets the channel alias  of channel from cookie.
*/

STORAGE.getAlias = function()
{
    return COOKIE.getCookie("storageAlias") || "";
}

/*
* Clears the channel alias  of channel from cookie.
*/

STORAGE.clearAlias = function()
{
    COOKIE.setCookie("storageAlias", "", -1, "/");
}

/*
* Sets the skin of player in cookie.
*/

STORAGE.setSkin = function(skin)
{
	
    COOKIE.setCookie("storageSkin", skin, this.eternity, "/");
}

/*
* Gets the skin of player from cookie.
*/

STORAGE.getSkin = function()
{
    return COOKIE.getCookie("storageSkin") || "";
}

/*
* Clears the skin of player from cookie.
*/

STORAGE.clearSkin = function()
{
    COOKIE.setCookie("storageSkin", "", -1, "/");
}
/*
* Sets the skin of player in cookie.
*/

STORAGE.setUnregisterInfo = function(unregister)
{
	
    COOKIE.setCookie("UnregisterInfo", unregister, this.eternity, "/");
}

/*
* Gets the skin of player from cookie.
*/

STORAGE.getUnregisterInfo = function()
{
    return COOKIE.getCookie("UnregisterInfo") || "";
}

/*
* Clears the skin of player from cookie.
*/

STORAGE.clearUnregisterInfo = function()
{
    COOKIE.setCookie("UnregisterInfo", "", -1, "/");
}
/*
* Sets the skin of player in cookie.
*/

STORAGE.setDisplayName= function(nameToDisplay)
{
	
    COOKIE.setCookie("nameToDisplay", nameToDisplay, this.eternity, "/");
}

/*
* Gets the skin of player from cookie.
*/

STORAGE.getDisplayName = function()
{
    return COOKIE.getCookie("nameToDisplay") || "";
}

/*
* Clears the skin of player from cookie.
*/

STORAGE.clearDisplayName = function()
{
    COOKIE.setCookie("nameToDisplay", "", -1, "/");
}
/*
* Sets the skin of player in cookie.
*/

STORAGE.setDisplayNM= function(nm)
{
	
    COOKIE.setCookie("nameDisplay", nm, this.eternity, "/");
}

/*
* Gets the skin of player from cookie.
*/

STORAGE.getDisplayNM = function()
{
    return COOKIE.getCookie("nameDisplay") || "";
}

/*
* Clears the skin of player from cookie.
*/

STORAGE.clearDisplayNM = function()
{
    COOKIE.setCookie("nameDisplay", "", -1, "/");
}

/*
* Sets the skin of player in cookie.
*/

STORAGE.setPublisherDisplayName= function(nm1)
{
	
    COOKIE.setCookie("Displayname", nm1, this.eternity, "/");
}

/*
* Gets the skin of player from cookie.
*/

STORAGE.getPublisherDisplayName = function()
{
    return COOKIE.getCookie("Displayname") || "";
}

/*
* Clears the skin of player from cookie.
*/

STORAGE.clearPublisherDisplayName = function()
{
    COOKIE.setCookie("Displayname", "", -1, "/");
}

/*
* Sets the skin of player in cookie.
*/

STORAGE.setGender= function(gender)
{
	
    COOKIE.setCookie("gender", gender, this.eternity, "/");
}

/*
* Gets the skin of player from cookie.
*/

STORAGE.getGender = function()
{
    return COOKIE.getCookie("gender") || "";
}

/*
* Clears the skin of player from cookie.
*/

STORAGE.clearGender = function()
{
    COOKIE.setCookie("gender", "", -1, "/");
}
/*
* Sets the user's name in cookie.
*/
STORAGE.setUserName = function(userName)
{
	//var val=padding_from(userName);   
	//alert(val);// change for encrypting username
    COOKIE.setCookie("sun", userName, this.eternity, "/");
}

/*
* Sets the owner of chennel in cookie.
*/

STORAGE.setOwner = function(owner)
{
	
    COOKIE.setCookie("storageOwner", owner, this.eternity, "/");
}

/*
* Gets the owner of chennel from cookie.
*/

STORAGE.getOwner = function()
{
    return COOKIE.getCookie("storageOwner") || "";
}

/*
* Clears the owner of chennel from cookie.
*/

STORAGE.clearOwner = function()
{
    COOKIE.setCookie("storageOwner", "", -1, "/");
}

/*
* Sets the guid of item in cookie.
*/

STORAGE.setGuid = function(item)
{
	
    COOKIE.setCookie("storageGuid", item, this.eternity, "/");
}

/*
* Gets the guid of item from cookie.
*/

STORAGE.getGuid = function()
{
    return COOKIE.getCookie("storageGuid") || "";
}

/*
* Clears the guid of item from cookie.
*/

STORAGE.clearGuid = function()
{
    COOKIE.setCookie("storageGuid", "", -1, "/");
}

/*
* Clears the user's name from cookie.
*/

STORAGE.clearUserName = function()
{
    COOKIE.setCookie("sun", "", -1, "/");
}

/*
* Gets the user's name from cookie.
*/

STORAGE.getUserName = function()
{
	//var val=COOKIE.getCookie("sun") || "";
	//alert(val);
    return COOKIE.getCookie("sun") || "";
}

/*
* Set the wsseHeader related to logged in user.
*/
STORAGE.setWsseHeader = function(wsseHeader)
{
	
    COOKIE.setCookie("storageWsseHeader", wsseHeader, this.eternity, "/");
}
/*
* clear the wsseHeader
*/

STORAGE.clearWsseHeader = function()
{
    COOKIE.setCookie("storageWsseHeader", "", -1, "/");
}

/*
* Set the wsseHeader
*/

STORAGE.getWsseHeader = function()
{
    return COOKIE.getCookie("storageWsseHeader") || "";
}

STORAGE.setPremiumCallback = function(calbackurl)
{
    //COOKIE.setCookie("storageSignupCallback", (calbackurl || ""), -1, "/");
    var tenMinutes = 15 * 60 * 1000;//milliseconds;
    var time = new Date().getTime() + tenMinutes;
    COOKIE.setCookie("storagePremiumCallback", calbackurl, new Date(time), "/");

}

STORAGE.clearPremiumCallback = function()
{
    COOKIE.setCookie("storagePremiumCallback", "", -1, "/");
}

STORAGE.getPremiumCallback = function()
{
    return COOKIE.getCookie("storagePremiumCallback") || "";
}

STORAGE.setGlobalTargetUrl = function(targetUrl)
{
	COOKIE.setCookie("storageGlobalTargetUrl", targetUrl, STORAGE.eternity, "/");
//    SESSION.params.global_target_url = targetUrl;
}

STORAGE.getGlobalTargetUrl = function()
{
    return COOKIE.getCookie("storageGlobalTargetUrl") || "";
//    return SESSION.params.global_target_url;
}

STORAGE.clearGlobalTargetUrl = function()
{
	COOKIE.setCookie("storageGlobalTargetUrl", "", new Date(), "/");
//    SESSION.params.global_target_url = null;
}


/*
* Sets the category id in cookie.
*/

STORAGE.setCategoryId = function(id)
{
	
    COOKIE.setCookie("categoryid", id, this.eternity, "/");
}
/*
* Gets the category id in cookie.
*/
STORAGE.getCategoryId  = function()
{
    return COOKIE.getCookie("categoryid") || "";
//    return SESSION.params.global_target_url;
}
/*
* Clears the category id in cookie.
*/
STORAGE.clearCategoryId= function()
{
	COOKIE.setCookie("categoryid", "", -1, "/");
//    SESSION.params.global_target_url = null;
}

/*
* Sets the category title in cookie.
*/

STORAGE.setCategoryTitle = function(id)
{
	
    COOKIE.setCookie("categorytitle", id, this.eternity, "/");
}
/*
* Gets the category title in cookie.
*/
STORAGE.getCategoryTitle  = function()
{
    return COOKIE.getCookie("categorytitle") || "";
//    return SESSION.params.global_target_url;
}
/*
* Clears the category title in cookie.
*/
STORAGE.clearCategoryTitle= function()
{
	COOKIE.setCookie("categorytitle", "", -1, "/");
//    SESSION.params.global_target_url = null;
}



/*
* Sets the status of user where he is logged in or not id in cookie.
*/

STORAGE.setUserLoggedin = function(id)
{
	
    COOKIE.setCookie("userLoggedin", id, this.eternity, "/");
}
/*
*  Get the status of user where he is logged in or not id in cookie.
*/
STORAGE.getUserLoggedin  = function()
{
    return COOKIE.getCookie("userLoggedin") || "";

}
/*
* Clears  the status of user .
*/
STORAGE.clearUserLoggedin= function()
{
	COOKIE.setCookie("userLoggedin", "", -1, "/");

}



/*
* Sets categoryid in cookie.
*/

STORAGE.setCategoryId= function(id)
{
	
    COOKIE.setCookie("categoryId", id, this.eternity, "/");
}

/*
* Gets the categoryid from cookie.
*/

STORAGE.getCategoryId = function()
{
    return COOKIE.getCookie("categoryId") || "";
}


/*
* Clears the categoryid from cookie.
*/


STORAGE.clearCategoryId = function()
{
    COOKIE.setCookie("categoryId", "", -1, "/");
}

LOGGER.defined("STORAGE");

///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// END ////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////


/*
//How make stubs:

SERVER.commandGetFutureGroups = function( )
{
//    this.sendMessageAuth("commandGetFutureGroups", {cmd:"pendingSubscriptions" },true );
    var group1 = {name:"alfa",  type:"gt_inviting", alias:"vb_helxet",email:"dvezhnin@hexlet.com", action:"invite"};
    var group2 = {name:"betta", type:"gt_private",  alias:"vb_helxet",email:"dvezhnin@hexlet.com", action:"subscribe"};

    var result = [group1, group2];
    SERVER.OnGetFutureGroups(result);
}
*/

/*
* Set the popup window at center of screen.
* parameter is div id of popup.
*/
	function setTopLeft(popUpId)
	{
		var element1=document.getElementById(popUpId);
		var INIT_TOP,INIT_LEFT;
		var TOP,LEFT;
		
		element1.style.display='block';
		
		var popWidth=element1.offsetWidth;
		var popHeight=element1.offsetHeight;
		
		// getting the top left coordinates of the container of this popup
		INIT_TOP=element1.style.top=element1.parentNode.style.top
		INIT_LEFT=element1.style.left=element1.parentNode.style.left
		
 		// Truncating the 'px' from the end of string
		INIT_TOP=Number(INIT_TOP.substr(0,INIT_TOP.length-2));
		INIT_LEFT=Number(INIT_LEFT.substr(0,INIT_LEFT.length-2));
		
		
		// getting the width and height of display window
		var  winWidth = 0, winHeight = 0, d = document;
			if (typeof (window.innerHeight) == 'number')///for netscape 
				{
					winWidth = window.innerWidth;
					winHeight = window.innerHeight;
				} 
			else
			if (d.documentElement && d.documentElement.clientHeight)///for internet explorer
				{
					winWidth = d.documentElement.clientWidth;
					winHeight = d.documentElement.clientHeight;
				} 
			else
			if (d.body && d.body.clientHeight) ///for fire fox
				{
					winWidth = d.body.clientWidth;
					winHeight = d.body.clientHeight;
				}
		
		// calculating the top left of this popup
		TOP=((winHeight/2) - (popHeight/2));
		LEFT=((winWidth/2) - (popWidth/2));
			
		// Checking and adjusting positions for multipli layered popups
		if(INIT_TOP>0 || INIT_LEFT>0)
		{
			TOP=TOP-INIT_TOP;
			LEFT=LEFT-INIT_LEFT;
		}
		
		// correcting negative coordinate error
		if(TOP<0)TOP=0;
		if(LEFT<0)LEFT=0;
		
		// assigning coordinated to this popup
		element1.style.top=TOP;
		element1.style.left=LEFT;		
		//alert("Window Width="+winWidth+"Window Height="+winHeight+"\n"+"Popup Width="+popWidth+"Popup Height="+popHeight+"\n"+"Popup Left="+LEFT+"Popup Top="+TOP);
	}
/*
* Sets the alignment of channel description popup used in view_channel_template.jsp.
*/

	function setTopLeftChannelDesc(popUpId)
	{
		var element1=document.getElementById(popUpId);
		var element2=document.getElementById("description");
		
		
		element1.style.display='block';
		
		var popWidth=element1.offsetWidth;
		var popHeight=element1.offsetHeight;

		var descWidth=element2.offsetWidth;
		var descHeight=element2.offsetHeight;
		
		
		
		// getting the top left coordinates of the container of this popup
		var INIT_TOP=element2.style.top;
		var INIT_LEFT=element2.style.left;
		
 		// Truncating the 'px' from the end of string
		INIT_TOP=Number(INIT_TOP.substr(0,INIT_TOP.length-2));
		INIT_LEFT=Number(INIT_LEFT.substr(0,INIT_LEFT.length-2));
			
		// calculating the top left of this popup
		TOP=INIT_TOP+descHeight;
		LEFT=INIT_LEFT;
			
		// Checking and adjusting positions for multipli layered popups
		if(INIT_TOP>0 || INIT_LEFT>0)
		{
			TOP=TOP-INIT_TOP;
			LEFT=LEFT-INIT_LEFT;
		}
		
		// correcting negative coordinate error
		if(TOP<0)TOP=0;
		if(LEFT<0)LEFT=0;
		
		// assigning coordinated to this popup
		element1.style.top=TOP;
		element1.style.left=LEFT;		
		alert("Popup Width="+popWidth+"Popup Height="+popHeight+"\n"+"Popup Left="+LEFT+"Popup Top="+TOP+"\n"+"Container Left="+INIT_LEFT+"Container Left="+INIT_TOP);
	}
	

	
	function setTopLeftChannelDesc(popUpId)
	{
		var element1=document.getElementById(popUpId);
		var INIT_TOP,INIT_LEFT;
		var TOP,LEFT;
		
		element1.style.display='block';
		
		var popWidth=element1.offsetWidth;
		var popHeight=element1.offsetHeight;
		
		// getting the top left coordinates of the container of this popup
		INIT_TOP=element1.style.top=element1.parentNode.style.top
		INIT_LEFT=element1.style.left=element1.parentNode.style.left
		
 		// Truncating the 'px' from the end of string
		INIT_TOP=Number(INIT_TOP.substr(0,INIT_TOP.length-2));
		INIT_LEFT=Number(INIT_LEFT.substr(0,INIT_LEFT.length-2));
		
		
		// getting the width and height of display window
		var  winWidth = 0, winHeight = 0, d = document;
			if (typeof (window.innerHeight) == 'number')///for netscape 
				{
					winWidth = window.innerWidth;
					winHeight = window.innerHeight;
				} 
			else
			if (d.documentElement && d.documentElement.clientHeight)///for internet explorer
				{
					winWidth = d.documentElement.clientWidth;
					winHeight = d.documentElement.clientHeight;
				} 
			else
			if (d.body && d.body.clientHeight) ///for fire fox
				{
					winWidth = d.body.clientWidth;
					winHeight = d.body.clientHeight;
				}
		
		// calculating the top left of this popup
			if(popUpId=="descLayer"){
			TOP=240//(240*winHeight)/1024;
			LEFT=(676*winWidth)/1280;
			}

		if(popUpId=="dobinfoLayer"){
			TOP=450//(450*winHeight)/1024;
			LEFT=(625*winWidth)/1280;
			}	


		if(popUpId=="dobInfoOldUserLayer"){		
			TOP=300;//(450*winHeight)/1024;
			LEFT=(820*winWidth)/1280;
			}		

			if(popUpId=="dobInfoIncompLayer"){		
			TOP=425;//(450*winHeight)/1024;
			LEFT=(850*winWidth)/1280;
			}		
		
				
			if(popUpId=="channelvisibility"){		
			TOP=840;//(450*winHeight)/1024;
			LEFT=(475*winWidth)/1280;
			}		
           if(popUpId=="handsetList"){
				TOP=650;
				LEFT=(355*winWidth)/1280;
			}
           

			
		// Checking and adjusting positions for multipli layered popups
		if(INIT_TOP>0 || INIT_LEFT>0)
		{
			TOP=TOP-INIT_TOP;
			LEFT=LEFT-INIT_LEFT;
		}
		
		// correcting negative coordinate error
		if(TOP<0)TOP=0;
		if(LEFT<0)LEFT=0;
		
		// assigning coordinated to this popup
		element1.style.top=TOP;
		element1.style.left=LEFT;		
		//alert("Window Width="+winWidth+"Window Height="+winHeight+"\n"+"Popup Width="+popWidth+"Popup Height="+popHeight+"\n"+"Popup Left="+LEFT+"Popup Top="+TOP);
	}


  function doSomething(e) {
        var posx = 0;
        var posy = 0;
        if (!e) var e = window.event;
        if (e.pageX || e.pageY)     {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)     {
            posx = e.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
        }
        
    }
    
/*
* Call on unload event of every page.
*/
     function confirmMe()
    {
		
		var remember=STORAGE.getRememberUser();
		var rememCheck=STORAGE.getRememberCheck();
	
		if(window.screenLeft >screen.width){
			

			if(remember=="" && rememCheck=="false"){
				
				STORAGE.clearUserName();
				STORAGE.clearWsseHeader();
				STORAGE.clearRememberUser();
			}
		
		}
		else{
		
		}

		
    }

/*
* Methods for calculating last Update for channels
*/


Date.prototype.toISO8601String = function (format, offset) 
{
    /* accepted values for the format [1-6]:
     1 Year:
       YYYY (eg 1997)
     2 Year and month:
       YYYY-MM (eg 1997-07)
     3 Complete date:
       YYYY-MM-DD (eg 1997-07-16)
     4 Complete date plus hours and minutes:
       YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
     5 Complete date plus hours, minutes and seconds:
       YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
     6 Complete date plus hours, minutes, seconds and a decimal
       fraction of a second
       YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)
    */
    if (!format) { var format = 6; }
    if (!offset) 
	{
        var offset = 'Z';
        var date = this;
    } else 
	{
        var d = offset.match(/([-+])([0-9]{2}):([0-9]{2})/);
        var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
        offsetnum *= ((d[1] == '-') ? -1 : 1);
        var date = new Date(Number(Number(this) + (offsetnum * 60000)));
    }
}


Date.prototype.setISO8601 = function (string) 
{
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}

function checkTimeZone() 
{
   var rightNow = new Date();
   var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
   var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
   var temp = date1.toGMTString();
   var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var temp = date2.toGMTString();
   var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
   var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);
   if (hoursDiffDaylightTime == hoursDiffStdTime) {
      
	  
	  //alert("Time zone is GMT " + hoursDiffStdTime + ".\nDaylight Saving Time is NOT observed here.");
	  return("false")
	  
   } else {
     // alert("Time zone is GMT " + hoursDiffStdTime + ".\nDaylight Saving Time is observed here.");
	  return("true")
   }
}
function isDSTOn() {
var dt=new Date();
 var cy=dt.getFullYear();
 var cm=parseInt(dt.getMonth())+1;
 var cd=parseInt(dt.getDate());
 
  //alert(cd+"/"+cm+"/"+cy);
 
 var thisYear, AprilDate, OctoberDate, MarchDateEU, OctoberDateEU, MarchDate, NovemberDate;
 thisYear = Math.round(parseInt(cy));

 AprilDate = (2+6 * thisYear - Math.floor (thisYear / 4) ) % 7 + 1;
 OctoberDate=  (31-( Math.floor (thisYear * 5 / 4) + 1) % 7);
 
 MarchDate = 14 - (Math.floor (1 + thisYear * 5 / 4) % 7);
 NovemberDate = 7 - (Math.floor (1 + thisYear * 5 / 4) % 7);
  
 MarchDateEU =  (31-( Math.floor (thisYear * 5 / 4) + 4) % 7);
 OctoberDateEU =  (31-( Math.floor (thisYear * 5 / 4) + 1) % 7);

var DSTStartMonth,DSTEndMonth;
var DSTStartDay,DSTEndDay;

if(thisYear>2006)
{
	DSTStartMonth=3;
	DSTStartDay=parseInt(MarchDate);	
	
	DSTEndMonth=11;
	DSTEndDay=parseInt(NovemberDate);
}
else
{
	DSTStartMonth=4;
	DSTStartDay=parseInt(AprilDate);	
	
	DSTEndMonth=10;
	DSTEndDay=parseInt(OctoberDate);
}

var answer="false"
if(cm>DSTStartMonth && cm<DSTEndMonth)
{
  	answer="true";
}
else if (cm==DSTStartMonth)
{
	if(cd>=DSTStartDay)answer="true";
}
else if(cm==DSTEndMonth)
{
	if(cd<=DSTEndDay)answer="true"
}
else answer="false";
 
 //alert(DSTStartDay+"/"+DSTStartMonth+"/"+cy);
 //alert(DSTEndDay+"/"+DSTEndMonth+"/"+cy);
 //alert(answer);
 return(answer);
}
function getElapsedTime(qty,oldDate,newDate)
{
	var d1 =oldDate ;
	var d2 =newDate;
	
	var second= 1000;
	var minute= second*60;
	var hour  = minute*60;
	var day   = hour*24;
	var week  = day*7;
	var month = day*30;
	var year  = day*365;
	
	var diff;
	
	if(qty=="second")     diff = Math.floor((d2-d1)/(second));
	else if(qty=="minute")diff = Math.floor((d2-d1)/(minute));
	else if(qty=="hour")  diff = Math.floor((d2-d1)/(hour));
	else if(qty=="day")   diff = Math.floor((d2-d1)/(day));
	else if(qty=="week")  diff = Math.floor((d2-d1)/(week));
	else if(qty=="month") diff = Math.floor((d2-d1)/(month));
	else if(qty=="year")  diff = Math.floor((d2-d1)/(year));
	

	return(diff);
}


function checkDiffrence(qty,serverTimestamp)
{
	var dstOffset=0
	if(checkTimeZone()=="false")
	{
		dstOffset=(1000*60*60);
		//alert(dstOffset);
	}
	if(isDSTOn()=="false")
	{
		dstOffset=0;
	}
	var current=new Date().toString();
	var old = new Date();
	old.setISO8601(serverTimestamp);
		
	
	timestamp1 = parseInt(Date.parse(old))+dstOffset;
    timestamp2 = Date.parse(current);
				
	
	
	var diff=getElapsedTime(qty,timestamp1,timestamp2);
	
	return(diff);
	
}
/*
*  Get the last update of channel by giving parameter "serverTimestamp".
*/
function getAge(serverTimestamp)
{
	var age;
	     if(serverTimestamp==null)
	{
			 age="No Updated Clips.";
	}
	else
	{
		 if(checkDiffrence("year",serverTimestamp)==1)age=checkDiffrence("year",serverTimestamp)+" year ago";
	else if(checkDiffrence("month",serverTimestamp)==1)age=checkDiffrence("month",serverTimestamp)+" month ago";
	else if(checkDiffrence("week",serverTimestamp)==1)age=checkDiffrence("week",serverTimestamp)+" week ago";
	else if(checkDiffrence("day",serverTimestamp)==1)age=checkDiffrence("day",serverTimestamp)+" day ago";
	else if(checkDiffrence("hour",serverTimestamp)==1)age=checkDiffrence("hour",serverTimestamp)+" hour ago";
	else if(checkDiffrence("minute",serverTimestamp)==1)age=checkDiffrence("minute",serverTimestamp)+" minute ago";
	else if(checkDiffrence("second",serverTimestamp)==1)age=checkDiffrence("second",serverTimestamp)+" second ago";


		 if(checkDiffrence("year",serverTimestamp)>1)age=checkDiffrence("year",serverTimestamp)+" years ago";
	else if(checkDiffrence("month",serverTimestamp)>1)age=checkDiffrence("month",serverTimestamp)+" months ago";
	else if(checkDiffrence("week",serverTimestamp)>1)age=checkDiffrence("week",serverTimestamp)+" weeks ago";
	else if(checkDiffrence("day",serverTimestamp)>1)age=checkDiffrence("day",serverTimestamp)+" days ago";
	else if(checkDiffrence("hour",serverTimestamp)>1)age=checkDiffrence("hour",serverTimestamp)+" hours ago";
	else if(checkDiffrence("minute",serverTimestamp)>1)age=checkDiffrence("minute",serverTimestamp)+" minutes ago";
	else if(checkDiffrence("second",serverTimestamp)>1)age=checkDiffrence("second",serverTimestamp)+" seconds ago";
	else if(checkDiffrence("year",serverTimestamp)<0)age="recently";
	}
	
	return(age);
}

String.prototype.wordWrap = function(m, b, c){
    var i, j, s, r = this.split("\n");
    if(m > 0) for(i in r){
        for(s = r[i], r[i] = ""; s.length > m;
            j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length
            || m,
            r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? b : "")
        );
        r[i] += s;
    }
    return r.join("\n");
}




function elaborateTimestamp(serverTimestamp)
{

	var dstOffset=0
	if(checkTimeZone()=="false")
	{
		dstOffset=(1000*60*60);
		//alert(dstOffset);
	}
	if(isDSTOn()=="false")
	{
		dstOffset=0;
	}
	var current=new Date().toString();
	var old = new Date();
	old.setISO8601(serverTimestamp);
		
	
	timestamp1 = parseInt(Date.parse(old))+dstOffset;
    var dt=new Date(timestamp1);

	 var cy=dt.getFullYear();
	 var cm=parseInt(dt.getMonth())+1;
	 var cd=parseInt(dt.getDate());
     var ch= parseInt(dt.getHours());
	 var dd=parseInt(dt.getMinutes());
     var ds=parseInt(dt.getSeconds());
	 var newDate=new Date(cy,cm,cd,ch,dd,ds);
	 var month=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec");
	 var monthText="";
	 for(var i=1;i<=12;i++){
		 if(i==cm){
			 //alert("h"+month[i]);
			 //alert(i+":"+cm)
                 monthText=month[i-1];
				}
	 }
	 var ampm="";
	if(ch>12 && dd<60){
       ampm="PM";
	}else
	{
		ampm="AM";
	}

	 var FinalDate="";
	 FinalDate=FinalDate+" "+monthText+" "+cd+", "+" "+cy+" "+ch+":"+dd+" "+ampm;
	//alert(cy+"::"+cm+":::"+cd+"::"+ch+"::"+dd+"::"+ds+"::"+newDate);
	//alert(d.getMonth);
	//alert(FinalDate);
	return(FinalDate);
	
}
/*Add to Message hide button display  */
function hidebtn(){

  document.getElementById('errorMessage').style.display='none';

} //end display

/* method for checking max length for all input tupe. except text area*/
function checkLen(x,y,idname,errorId)
{
	var error="";

if (y.length > (x.maxLength-1))
  {
    error ="The max limit of "+idname+" is exceeded. Should not be longer than "+(x.maxLength-1)+" chars. Please shorten it to fit in the max limit."; 
	   document.getElementById(errorId).innerHTML=error;
       document.getElementById(errorId).style.display="block";
}
else{
     document.getElementById(errorId).innerHTML=error;
       document.getElementById(errorId).style.display="none";
}
}

/* method for checking max length for  textarea*/
function checkLenTextarea(id,idname,errorId)
{
	var error="";

if (id.length > 1024)
  {
    error ="The max limit of "+idname+" is exceeded. Should not be longer than 1024 chars. Please shorten it to fit in the max limit."; 
	   document.getElementById(errorId).innerHTML=error;
       document.getElementById(errorId).style.display="block";
       window.scrollTo(0,0);
}
else{
     document.getElementById(errorId).innerHTML=error;
       document.getElementById(errorId).style.display="none";
}
}
