//#Timer
var beforeload;

//#Ajax calls
var oWUser = new WADJAX('User', { statusBar: false });                  //# -
var wjxProfile = new WADJAX('Profile', {});                             //# -
var wjxShhProfile = new WADJAX('Profile', { statusBar: false });        //# - 
var wjxLabel = new WADJAX('Labels', {});                                //# handle feed actions
var wjxContacts = new WADJAX('Contacts', { statusBar: false });         //# handle contacts actions

var senderID;
var senderUID;
var senderUID_number;
var senderUID_current   = profileInfo.ownerWadjaID;

//#Store labels by category-autocomplete
var autocompleteValues = new Meio.Element.List();
var pushstart = 0; //set on/off when to push new feeds

//#Misc variables
var refTimer = false;
var SMSpay, PicFB;
var cLabelID = 8;
var LabelInfo = null;
var FollowLink = 1; //1: Follow, 2: Stop following
var following = false;
var ComposeTimeout;
var BodyTimeout;
var searchCategory = '';
var leftSide = ((profileInfo.profileBelongsToViewer || !profileInfo.isLoggedIn) ? '' : ' | ');
var selectedLabelName = '';
var mediaID = 0;
var Twitter = new Array();
var TwitterAutoPost = false;
var PreLabelID=-1;
var hide_overlay;
var maxchar=500;//#compose form max characters
var UIView=0;//#0:list view, 1:thumb view
var wHtmlCanvas = $('dvStream');    //#UI

//#Metatags feature
var MetaInfo = false;
var MetaInfoValue = '';
var MetaThumb='';
var MetaThumblist =0;
var isDomReady = false;

window.addEvent('domready', function () {
    jsHelper.logolink();			//!Handle home-logo
    jsHelper.anonymuspost();		//!Anonymous postings coming from the homepage
    jsHelper.attachments();			//!Attach link/youtube/photos
    jsHelper.handlePushfeedbar();	//!Add event on push-feed bar
    jsHelper.handleSendButton();	//!Add event on send-compose button
   	jsHelper.handleTwitterButton();	//!Handle twitter button-show/hide
    jsHelper.handleWadjaThinking(); //!Add event on message body-wadja thinking
    jsHelper.handleSearch();		//!Handle search requests
    jsHelper.handleExternalFeeds(); //!Handle external feeds
 	jsHelper.handleAutosuggest();	//!Handle compose form autosuggest
	jsHelper.handleTwitterCon();	//!Handle twitter connections
    jsHelper.handleLabelDropdowns();//!Handle label dropdowns-My, Follow, Every
    isDomReady = true;				//!On domready
    jsHelper.handleStart();			//!Load first feeds
});

var wProfile = {
    Compose: {
        BodyLength: 0,
        From: 0,
        AutoSuggest: { Obj: false, Results: false },
        SetFrom: function (q, t) { wProfile.Compose.From = q; },//#stopped->$('openID').innerHTML = 'from: ' + t + '<span class=\"arrowOn marL3\">&nbsp;</span>'; 
        Send: function () {
        
           var txtBodyMessage = $('txtBody').value;
           if ($('txtBody').hasClass('type_message'))
                txtBodyMessage = '';

           var txtMessageTo = $('txtTo').value;
           if ($('txtTo').hasClass('type_message'))
                txtMessageTo = '';

           if (($('txtBody').value == '' || $('txtBody').hasClass('type_message')) && MetaInfoValue == '' && mediaID==0) {
                Notify.topBarOn('Message cannot be empty', 'red', 5);
                return;
            }
            
            $('profile_compose_send').disabled = 1;
            Notify.spinnerOn('Sending...', 'Still sending', 5);
            wjxShhProfile.send('Send', txtBodyMessage, wProfile.Compose.From, mediaID, MetaInfoValue,txtMessageTo, wProfile.Compose.Response);
            
            MetaTags.remove();//clear if any metainfo found
            $('txtBody').setStyle('height','46px');//restore textbox size
        },
        Response: function (r) {
            $('profile_compose_send').disabled = 0;
            Notify.spinnerOff('Done', 5);
            if (r.error != null) {
                Notify.topBarOn(r.error, 'red', 7);
                return;
            }

            var r = JSON.decode(r.value);

            if (r.Error) {
                Notify.topBarOn(r.Message, 'red', 7);
            } else if (r.Cost) {
                SMSpay = new Facebox({
                    url: '/user/sms.aspx',
                    width: 500,
                    title: 'SMS confirmation',
                    submitValue: 'Send SMS',
                    submitFunction: function () {
                        wjxProfile.send('Pay', function (res) {
                            if (res.value != null && res.value == "0") {
                                SMSpay.close();
                                Notify.topBarOn("No enough points!", 'red', 7);
                                return;
                            }
                            SMSpay.close();
                            Notify.topBarOn("Success!", 'osfp', 7);
                            setTxtBodyText();
                            DeletePhoto();
                            wjxLabel.send('GetFeedInfo', r.FeedID, function (res) {
                                if (res.error) return;
                                var r = JSON.decode(res.value);
                                if (profileInfo.viewerID == profileInfo.ownerID && wProfile.Current.LabelID == 0)
                                    wProfile.showNew();
                                else {
                                    var array = new Array();
                                    array.push(r);
                                    wProfile.Helper.Loaded.push(r.FeedID);
                                    wProfile.Render.Start(array, true);
                                }
                            });
                            //wProfile.showNew();
                        });
                    },
                    cancelValue: 'Cancel',
                    cancelFunction: function () {
                        SMSpay.close();
                    },
                    footerLink: true, // adds a link before submit buttons
                    footerLinkHref: '',
                    footerLinkText: 'You have ' + profileInfo.points + ' points'
                });
                SMSpay.show();
            } else {
                
                setTxtBodyText();
//                var isMessage = document.location.hash.Contains('!inbox/');
//                if (isMessage) {
//                     Notify.topBarOn("Success!", 'osfp', 1);
//                     (function () {
//                            document.location.hash = '!My/2/1';
//                        }).delay(1 * 1000);                   
//                     return;
//                }
                Notify.topBarOn("Success!", 'osfp', 7);
                var feedArray = r.FeedID.split(',');
                for (var i = 0; i < feedArray.length; i++) {
                    wjxLabel.send('GetFeedInfo', feedArray[i], function (res) {
                        if (res.error) return;
                        var r = JSON.decode(res.value);
                        if ($('photo_attached')){
                            $('photo_attached').addClass('dnd');
                            $('link_attach_photo').removeClass('uploadMediaAtt');
                            $('link_attach_photo').addClass('uploadMedia');
                        }
                        mediaID = 0;
                        if (profileInfo.viewerID == profileInfo.ownerID && wProfile.Current.LabelID == 0)
                            wProfile.showNew();
                        else {
                            var array = new Array();
                            array.push(r);
                            wProfile.Helper.Loaded.push(r.FeedID);
                            wProfile.Render.Start(array, true, false, true);
                        }
                    });
                    //wProfile.showNew();
                }
            }
        },
        BodyType: function (event) {
            //#handles keyup event on the Body textbox
            clearTimeout(BodyTimeout);
            BodyTimeout = setTimeout(function () {
                if ($('txtBody').value !== '') {
                    try {
                        if (profileInfo.UseBitly)
                            bootloader.load('/user/plugins/jbitly.js', function () {
                                        BitLy($('txtBody').get('value'));
                                });
                    }
                    catch (err) {
                        ///wait until it loads the js file
                    }
                    //#count lines and toggle textarea height
                    theLines= countLines($('txtBody').value,10);
                    if (theLines>4 && theLines<7)
                        $('txtBody').setStyle('height','99px');
                    else if (theLines>=7)
                        $('txtBody').setStyle('height','130px');
                    else if (theLines<=4)
                        $('txtBody').setStyle('height','46px');
                    //#end of counting lines

                    //#count characters
                    $('dvCounter').innerHTML = maxchar - $('txtBody').value.length;
                    var curChars=maxchar - $('txtBody').value.length;

                    if (maxchar==160)
                    {
                        $('dvCounter').removeClass('dnd');
                        if (curChars==0 || curChars<0)
                            $('dvCounter').setStyle('color','#D40D12');
                        else
                            $('dvCounter').setStyle('color','#000000');
                    }
                    else
                    {   //#for text display counter only when less than zero
                
                        if (curChars==0 || curChars<0)
                        {
                            $('dvCounter').removeClass('dnd');
                            $('dvCounter').setStyle('color','#D40D12');
                        }
                        else
                        {
                            $('dvCounter').addClass('dnd');
                            $('dvCounter').set('html',maxchar);
                            $('dvCounter').setStyle('color','#000000');
                        }
                    }
                } 
                else {
                    MetaTags.remove();///#GetMeta info/ if link removed then reset function
                }
            }, 250);
        },
        Type: function (event) {
            clearTimeout(ComposeTimeout);
                ComposeTimeout = setTimeout(function () {
                if($('txtTo').value !== '') {
                    wjxShhProfile.send('WdjThnk', $('txtBody').value, $('txtTo').value, wProfile.Compose.WadjaThinking);
                }
                else
                {
                    $('dvCounter').innerHTML = maxchar;
                    var selectedLabelID = parseInt(wProfile.Current.LabelID);
                    var postVar = GetUserAndLabel(selectedLabelID);
                    if (!profileInfo.profileBelongsToViewer && postVar == '')
                            postVar = '@' + profileInfo.ownerWadjaID + ' ';
                        else if (profileInfo.profileBelongsToViewer && postVar == '')
                            postVar = '@';
                    var smsVar = '+';
                    if (!profileInfo.profileBelongsToViewer && profileInfo.ownerVerified === 'true')
                        smsVar = '+' + profileInfo.ownerWadjaID + ' ';
                    $('sendNote').innerHTML = '<a class=\"blueSms\" href=\"javascript:SetTextBox(\''+postVar+'\');\">Post (@)</a> or <a  class=\"greenSms\" href=\"javascript:SetTextBox(\''+smsVar+'\');\">SMS (+)</a>';
                    $('smsFromDDL').innerHTML = '';
                    ComposeOverlay.Hide();
                    //MetaTags.remove();///#GetMeta info/ if link removed then reset function
                }
            }, 250);
            

            //            event = event || window.event;             // gets the event in ie or ns
            //            kCode = event.keyCode || event.which;
            //            var k = event.key;
            //            if (k == 'space' || k == ',' || k == ';')
            //                wjxShhProfile.send('WdjThnk', $('txtBody').value, wProfile.Compose.WadjaThinking);

            //            var temp = $('txtBody').value.length;
            //            //$('dvCounter').innerHTML = (260 + wProfile.Compose.BodyLength) - $('txtBody').value.length;
            //$('dvCounter').innerHTML = 260 - wProfile.Compose.BodyLength;

        },
        WadjaThinking: function (r) {
            wProfile.Compose.BodyLength = 0;
            maxchar = 500;//#max chars

            if (r.error != null) {
                //Notify.topBarOn(r.error, 'red', 7);
                return;
            }

            var wdjThnk = "";
            r = JSON.decode(r.value);
            var selectedLabelID = parseInt(wProfile.Current.LabelID);
            var postVar = GetUserAndLabel(selectedLabelID);
            if (!profileInfo.profileBelongsToViewer && postVar == '')
                    postVar = '@' + profileInfo.ownerWadjaID + ' ';
                else if (profileInfo.profileBelongsToViewer && postVar == '')
                    postVar = '@';
            var smsVar = '+';
            if (!profileInfo.profileBelongsToViewer && profileInfo.ownerVerified === 'true')
                smsVar = '+' + profileInfo.ownerWadjaID + ' ';
            if(r.isSMS) {
                $('sendNote').innerHTML = 'SMS to: ';
                $('smsFromDDL').innerHTML = " from <span id=\"compose_from_senderID\" class=\"labelballon cursor f13\" onclick=\"ToggleSenderID(0);\" onmouseover=\"ToggleSenderID(1);\" onmouseout=\"ToggleSenderID(2);\">" + senderUID_current + "</span><span id=\"compose_from_senderID_tip\" class=\"dnd f11\"> &larr; change sender id</span>";
                maxchar = 160;//#SMS max characters
                // change style when SMS               
            }
            else {
                $('sendNote').innerHTML = 'Post to: ';
                $('smsFromDDL').innerHTML = '';
                maxchar = 500;//#max chars                    
            }
            if (r.Users.length == 0) // Post to My profile
            {
                if (r.Labels.length == 0) {
                    wdjThnk = "<a class=\"blueSms\" href=\"javascript:SetTextBox('" + postVar + "');\">Post (@)</a> to My (Home) label or <a class=\"greenSms\" href=\"javascript:SetTextBox('" + smsVar + "');\">Send SMS (+)</a>";
                }
                else {
                    wdjThnk = "<a class=\"blueSms\" href=\"javascript:SetTextBox('" + postVar + "');\">Post (@)</a> to My (";
                    for (j = 0; j < r.Labels.length; j++) {
                        wdjThnk += (j == 0 ? "" : ", ") + r.Labels[j].name;
                    }
                    wdjThnk += (") " + (r.Labels.length == 1 ? "label" : "labels"));
                    //don't show:wdjThnk += " or <a class=\"greenSms\" href=\"javascript:SetTextBox('" + smsVar + "');\">Send SMS (+)</a>";
                }
                
            } else if (r.UsersAndLabels == null) {
                if (r.isSMS) {
                    wdjThnk = "SMS to";
                    for (i = 0; i < r.Users.length; i++) {
                        wdjThnk += (i == 0 ? " " : ", ") + r.Users[i];
                    }
                    //wdjThnk +=" from <span id=\"compose_from_senderID\" class=\"labelballon cursor f13\" onclick=\"ToggleSenderID(0);\" onmouseover=\"ToggleSenderID(1);\" onmouseout=\"ToggleSenderID(2);\">" + senderUID_current + "</span><span id=\"compose_from_senderID_tip\" class=\"dnd f11\"> &larr; change sender id</span>";
                }
                else {
                    wdjThnk = "";
                    for (i = 0; i < r.Users.length; i++) {
                        if (profileInfo.viewerName.toLowerCase() != r.Users[i].toLowerCase())
                            wdjThnk += "<a class=\"blueSms\" href=\"javascript:SetTextBox('" + postVar + "');\">Post (@)</a> to " + r.Users[i] + " (Message) label" + (i == r.Users.length - 1 ? "" : ", ");
                        else
                            wdjThnk += "<a class=\"blueSms\" href=\"javascript:SetTextBox('" + postVar + "');\">Post (@)</a> to My (Message) label" + (i == r.Users.length - 1 ? "" : ", ");
                    }
                    //wdjThnk += " or <a class=\"greenSms\" href=\"javascript:SetTextBox('" + smsVar + "');\">Send SMS (+)</a>";
                }
            }
            else {
                wdjThnk = "<a class=\"blueSms\" href=\"javascript:SetTextBox('" + postVar + "');\">Post (@)</a> to";
                for (i = 0; i < r.UsersAndLabels.length; i++) {
                    if (r.UsersAndLabels[i].DetailsID != profileInfo.viewerID) {
                        wdjThnk += (i == 0 ? " " : ", ") + r.UsersAndLabels[i].Name + " (";
                        for (j = 0; j < r.UsersAndLabels[i].Labels.length; j++) {
                            wdjThnk += (j == 0 ? "" : ", ") + r.UsersAndLabels[i].Labels[j].Name;
                        }
                        wdjThnk += (") " + (r.UsersAndLabels[i].Labels.length == 1 ? "label" : "labels"));
                    }
                    else {
                        wdjThnk += (i == 0 ? " " : ", ") + "My (";
                        for (j = 0; j < r.UsersAndLabels[i].Labels.length; j++) {
                            wdjThnk += (j == 0 ? "" : ", ") + r.UsersAndLabels[i].Labels[j].Name;
                        }
                        wdjThnk += (") " + (r.UsersAndLabels[i].Labels.length == 1 ? "label" : "labels"));
                    }
                }
                //wdjThnk += " or <a class=\"greenSms\" href=\"javascript:SetTextBox('" + smsVar + "');\">Send SMS (+)</a>";
            }

            //wProfile.Compose.BodyLength = $('txtBody').value.length - r.BodyLength;
            //wProfile.Compose.BodyLength = r.BodyLength;          
            ComposeOverlay.SetText(wdjThnk, r.isSMS);
            ComposeOverlay.Show();
//            var SendHover;
//            if ($('send_hovercraft')) {
//                SendHover = $('send_hovercraft');
//                SendHover.innerHTML = '<div class=\"share-arrow-post\">&nbsp;</div><div class=\"body\"><div>'+wdjThnk+'</div><div class=\"closePost\"><a class=\"f_r\" href=\"\">Close <span class=\"closeIcon\">&nbsp;</span></a></div></div>';
//                SendHover.setStyle('display', 'block').fade('in');
//                        SendHover.setStyles({
//                            top: '71px',
//                            zindex: '1000',
//                            width: '290px',
//                            right: '3px'
//                        });
//            }
            //$('dvFound').getElement('span').innerHTML = wdjThnk;
            
        }
    },
    Current: { DetailsID: profileInfo.ownerID, Category: 'My', LabelID: 8, Filter: 0, Page: 1, MinID: 0, FeedsPending: 0, ViewerID: profileInfo.viewerID }, // What data to show
    CurrentSearch: { Page: 1, Category: '', Keyword: '' },
    Helper: { Loaded: [], Pending: [], Labels: [] }, // Helper functions
    Render: {
        More: function () {
            //more-loading
            if ($('feeds_more_button')) {
                $('feeds_more_button').set('disabled', true);
                $('feeds_more_button').set('value', $('feeds_more_button').get('value') + '...');
            }
            //end of more-loading
            wProfile.Load(wProfile.Current.DetailsID, wProfile.Current.Category, wProfile.Current.LabelID, (wProfile.Current.Page += 1), false);
        },
        Start_RC1: function(r, b, srch, postToMsg) //#beta rich view
        {
            //#onError
            if (r.error != null)
            {
                Notify.topBarOn('Oops! Too many feeds. Please try again later * on RC1: '+r.error, 'red', 6)
                return;//#stop here
            }
            
            //#declare variables
            var wHtmlPackage = JSON.decode(r.value); //#Data-render
            var wHtmlRows=15;                   //#How many rows to display

            var wHtmlFdID,wHtmlFdBody,wHtmlFdAuthor,wHtmlFdDate,wHtmlFdTools,wHtmlFdLabels,wHtmlFdRecipients; //#feed
            var wHtmlFdContacts;                //#contacts
            var wHtmlFdSearch;                  //#search
            var wHtmlFdConversation;            //#conversation
            var wHtmlFdAttachment;              //#Youtube, photo, url e.t.c
           
            var wHtmlFdHead;                    //#first feed

            //#onTimeout or any other error
            if (wHtmlPackage==null) {
                Notify.topBarOn('Too many feeds. Please try again later.', 'red', 6)
                return;
            }
            
            //#BEGIN
            //#If everything is ok then start rendering-how many rows to display each time
            if (wHtmlPackage.length > parseInt(wHtmlRows))
                wHtmlRows = 15;
            else
                wHtmlRows = wHtmlPackage.length;

            //#Translate content
            for (i = 0; i < wHtmlRows; i++) {
                //**************************************** 0 ******************************************************
                wHtmlFdID   = wHtmlPackage[i].FeedID;     //#feed id
                wHtmlFdBody = wHtmlPackage[i].Body;       //#feed body text
                
                //**************************************** 1 ******************************************************
                //#Declare pagelet-feed, object
                var pageLet         = new Element('div'); //#container
                var pageLetBlock    = new Element('div'); //#block of content
                var pageLetHeader   = new Element('div'); //#header
                var pageLetPhotoBg  = new Element('div'); //#background image  
                var pageLetText     = new Element('div'); //#body text  
                var pageLetLabels   = new Element('div'); //#labels     
                var pageLetFooter   = new Element('div'); //#footer
                
                var feedHover;
                if ($('feed_hovercraft')) {
                    feedHover = $('feed_hovercraft');
                    feedHover.set('opacity', 0);
                }
                       
                if ($('thumb_open')) {
                    $('thumb_open').addEvents({
                        'mouseenter': function () {          
                        },
                        'click': function () {
                            feedHover.setStyle('display', 'block').fade('in');                            
                            feedHover.removeClass('dnd');                        
                            feedHover.setStyles({
                                top: '0px',
                                zindex: '1000',
                                left: '0px',
                                width:'100%',
                                height:'100%'
                            });             
                        }
                    });
                }
                if ($('closePopFeed')) {
                    $('closePopFeed').addEvents({
                    'onclick': function () {
                            feedHover.fade('out');
                            feedHover.setStyles({
                                zindex: '-1'
                            });
                        }
                   });
                }

                //**************************************** 2 ******************************************************
                //#- MARK
                //#- Recipients
                //#- header-loop conversation when the owner is not the reciepient
                //#- FROM
                //#- FROM/TO CLASS-drop white boxes-recipient, sender
                var cssFrom,cssTo;
                var cssSep,cssSepArrow;
                var uiRecipient;

                if (wHtmlPackage[i].DetailsID == wProfile.Current.DetailsID )
                {
                    cssTo = 'whiteDVTo';
                    cssFrom = '';
                    cssSep = 'toDV';
                    cssSepArrow='arrow_to';
                   
                }
                else if (wHtmlPackage[i].Recipients.length==0 && !wHtmlPackage[i].isThirdParty)
                {
                    cssTo = 'padL8';
                    cssFrom = 'whiteDVFrom';
                    cssSep = 'fromDV';
                    cssSepArrow='arrow_from';
                }
                else
                {   
                    cssTo = 'padL8';
                    cssFrom = 'whiteDVFrom';
                    cssSep = 'fromDV';
                    cssSepArrow='arrow_from';
                }
                //#SENDER
                pageLetHeader.appendChild(new Element('div', {'class':''+cssFrom,'html':'<img  src=\"'+wHtmlPackage[i].Thumbnail+'"/> <a style=\"\" href=\"\">'+wHtmlPackage[i].WadjaID+' ('+wHtmlPackage[i].Name+')</a>'}));
                pageLetHeader.appendChild(new Element('div', {'class':''+cssSep,'html':'<span class=\"'+cssSepArrow+'\">&nbsp;</span>'}));/*<span class=\"'+cssSepTextClass+'\">&nbsp;'+cssSepText+'&nbsp;</span>*/
                //#RECIPIENT(S)
                if (wHtmlPackage[i].isThirdParty) //#Third party
                    uiRecipient = '<img src=\"'+wHtmlPackage[i].ExternalUserThumbnailURL+'\"/> <a>'+wHtmlPackage[i].ExternalUserFullnameURL +'</a>';
                else
                {
                    //#One recipient
                    //#Multiple recipients
                    var uiPic;
                    if (wHtmlPackage[i].Recipients[0].ImageURL == null)
                        uiPic = '';
                    else
                        uiPic = '<img src=\"'+wHtmlPackage[i].Recipients[0].ImageURL.replace("_s.", "_n.")+'\"/>';
                    
                    if (wHtmlPackage[i].Recipients.length == 1)
                        uiRecipient = uiPic + ' <a>'+wHtmlPackage[i].Recipients[0].WadjaID+' ('+wHtmlPackage[i].Recipients[0].Name+')</a>';
                    else
                    {   
                    //#Multiple recipients are only for inobx-messages
                        uiRecipient = uiPic + '<a>'+wHtmlPackage[i].Recipients[0].WadjaID+' ('+wHtmlPackage[i].Recipients[0].Name+') *</a>';
                    }
                }

                if (wHtmlPackage[i].Recipients.length>0 || wHtmlPackage[i].isThirdParty )
                    pageLetHeader.appendChild(new Element('div', {'class':''+cssTo,'html':uiRecipient}));

                //#feed container .................................................................................
                pageLet.className = "thumb_view pageletClass psRel";
                pageLet.setAttribute("id", 'pageLet_' + wHtmlFdID);
                ///
                //#- MARK
                //#list all labels applied on current feed ........................................................
                pageLetHeader.className ="thumb_view_header";//#recipients placeholder
                ///
                //#- MARK /FEED BODY TEXT
                //#else display only text .........................................................................
                pageLetText.className="thumb_view_text";
                //#- MARK /LABELS
                //#Labels div ............................................................................... 
                pageLetLabels.className="thumb_labels";
                
                //#- MARK /TOOLS
                //#footer tools-bar ...............................................................................
                pageLetFooter.className="thumb_toolbar";
                
                //**************************************** 3 ******************************************************
                 //#- MARK
                //#if photo then display bg-image and thumb info.................................................................
                //pageLetPhotoBg.setAttribute("style","background: transparent url(http://im.rediff.com/movies/2008/apr/01spotted.jpg) center center no-repeat;");
                //pageLetPhotoBg.className ="thumb_view_photo";
                //pageLetPhotoBg.setAttribute("id","thumb_photo_flip");
                //#- MARK
                //#if photo then display bg-image and thumb info.................................................................
                //pageLetBlock.setAttribute("id", "thumb_open");
                //pageLetBlock.className="thumb_info";
                
               
                //photo background
                //pageLetPhotoBg.appendChild(new Element('span', {'class':'','html':'', 'id':''}));

                //#feed format text when no Background
                pageLetText.appendChild(new Element('div', {'class':'','html':'&#8220;&nbsp;'+wHtmlFdBody}));
                pageLetText.appendChild(new Element('div', {'class':'thumb_date','html':wProfile.Render.DateDiff(wHtmlPackage[i].Date)}));

                //#feed format text
                //#if no-photo then do not display the div below.
                pageLetBlock.appendChild(new Element('div', {'class':'thumb_text','html':'&#8220;&nbsp;'+wHtmlFdBody}));
                
                //#feed format date
                pageLetBlock.appendChild(new Element('div', {'class':'thumb_date','html':wProfile.Render.DateDiff(wHtmlPackage[i].Date)}));
                
                //#feed labels-limit to two
                var uiAttachedlabels='';
                for (j = 0; j < wHtmlPackage[i].Labels.length; j++) {
                        if (j<=1)
                            uiAttachedlabels = uiAttachedlabels + '<span id=\"users"><span class=\"lblBox b_r '+wHtmlPackage[i].Labels[j].style+'\"><a href=\"\">'+wHtmlPackage[i].Labels[j].name.replace("\'", "\\'") +'</a></span>';//<span title=\"Remove label\">x</span>
                        else
                            j = wHtmlPackage[i].Labels.length;
                }
                pageLetLabels.appendChild(new Element('div', {'class':'','html':uiAttachedlabels}));

                //pageLetLabels.appendChild(new Element('div', {'class':'','html':'<span id=\"users"><span class=\"lblBox b_r lblNotes\"><a>Home</a><span title=\"Remove label\">x</span></span><span class=\"lblBox b_r lblCountry_GR\"><a>Greece</a><span title=\"Remove label\">x</span></span></span>'}));
                
                //#feed tools
                if (profileInfo.isLoggedIn)//#if logged in
                {
                    if (profileInfo.viewerID == wHtmlPackage[i].DetailsID)//#if viewer is the owner of the feed
                    {
                        pageLetFooter.appendChild(new Element('a', {'class':'lblBox lblBoxApply b_r f_r','html':'<span class="cursor applyLabel">Label</span><span class="cursor applyLabelArrow">&nbsp;</span>', 'title':'Apply label on this feed'}));
                        pageLetFooter.appendChild(new Element('span', {'class':'applyStar','html':'&nbsp;'}));
                        pageLetFooter.appendChild(new Element('span', {'class':'applyTrash','html':'&nbsp;'}));
                    }
                }
                
                //pageLet.appendChild(pageLetPhotoBg);
                pageLet.appendChild(pageLetHeader);
                //pageLet.appendChild(pageLetText);
                pageLet.appendChild(pageLetBlock);
                pageLet.appendChild(pageLetLabels);
                pageLet.appendChild(pageLetFooter);
                
                //#Rendering completed and attached
                wHtmlCanvas.removeClass('dvProfFeeds');//#thumb view class
                wHtmlCanvas.addClass('thumb_view_profile');//#thumb view class
                wHtmlCanvas.appendChild(pageLet);
            }
        },
        Start: function (r, b, srch, postToMsg) {
           
            //#Switch views-list, thumb
            if (UIView == 1 )
            {
                //#Start-Rendering thumb view.
                wProfile.Render.Start_RC1(r, b, srch, postToMsg);
                return;
            }
            else
            {
                //#restore list view styles
                if (wHtmlCanvas.hasClass('thumb_view_profile'))
                {
                    wHtmlCanvas.addClass('dvProfFeeds');//#thumb view class
                    wHtmlCanvas.removeClass('thumb_view_profile');//#thumb view class
                }
            }

            //#debug:calculate the current time in afterload
            //#debug:var afterload = (new Date()).getTime();
            //#debug: /* now use the beforeload and afterload to calculate the seconds */
            //#debug:var secondes = (afterload-beforeload)/1000;
            //#debug:$('wzilla').removeClass('dnd');
            //#debug:$('wzilla').set('html',secondes);

            // Overlay when typing a post: Start
            var SendHover;

            if ($('send_hovercraft')) {
                SendHover = $('send_hovercraft');
                SendHover.set('opacity', 0);
            }

            // Overlay when typing a post: End

            //...Set compose box text
            setTxtBodyText();
            //...Make drop-downs style active
            jsHelper.handleDropDowns();
            //...Custom profile settings
            jsHelper.handleCustomprofiles();
            //...Update Inbox Counter
            wProfile.InboxCounter();
            //----------------------------------------------------------------------------------------
            //...if search feeds initialize search variables
            var addTop = (b !== undefined);
            var isFromSearch = (srch !== undefined);
            if(srch !== undefined)
                isFromSearch=srch;
            else
                isFromSearch=false;
            if (!isFromSearch)  jsHelper.resetSearchElements();
            //...if new post initialize variables
            var postToMessage = (postToMsg !== undefined);
            if(postToMsg !== undefined)
                postToMessage=postToMsg;
            else
                postToMessage=false;
            //...if Load Feeds, not Yellow Bar Click
            if (!addTop) { 
                if (r.error != null) {
                    Notify.topBarOn(r.error, 'red', 7);
                    return;
                }
                r = JSON.decode(r.value);
            } else {
                wProfile.Helper.Pending = [];
            }

            var isMessage = document.location.hash.Contains('!inbox/');
            if (isMessage && !postToMessage) {
                wProfile.Current.LabelID = -1;
                $('dvStream').empty();

                pushstart == 1; //stop pushing new feeds
            }
            else
                pushstart == 0; //start pushing new feeds

            if (wProfile.Helper.Loaded.length == 0) {
                var myFx = new Fx.Scroll(window).toTop(); //.toElement('dvStream');
                $('dvStream').empty();
            }

            var frag = document.createDocumentFragment();
            $('aNewFeeds').addClass('dnd');
            $('newfeeds_wrapper').addClass('dnd');
            
            if (isMessage && !postToMessage) $('dvMore').addClass('dnd');
            else if (r != null && r.length == 0) $('dvMore').addClass('dnd');
            else if (r[0].NoFeeds <= wProfile.Current.Page*10 && wProfile.Current.MinID == 0) $('dvMore').addClass('dnd');
            else $('dvMore').removeClass('dnd');
            
            var pendingLength = 0;
            
            //#on db timeout
            if (r==null)
            {
                Notify.topBarOn('Too many feeds. Please try again later.', 'red', 6)
                return '';
            }


            if (r.length > 15 && !isMessage)
                pendingLength = 15;
            else
                pendingLength = r.length;

            var inRecipients = false; //If user is in the recipients then do something-used for feed toolbar

            for (i = 0; i < pendingLength; i++) {
                if (!addTop &&  wProfile.Helper.Loaded.indexOf(r[i].FeedID) > -1) continue; // If Feed is already displaying, skip to next

                // #wadzilla
                // un-comment this line for testing: if (i == 0) alert(JSON.encode(r[i]));
                // #end of wadzilla

                var dvFeed = new Element('div'); // create a div container

                dvFeed.setAttribute("id", 'feed_' + r[i].FeedID);
                dvFeed.setAttribute("class", "feedMask"); // hide feed-we need this for the reveal effect

                if (r[i].ConversationUnreadCounter > 0) {
                    dvFeed.addClass('unread');
                }
                var fromImageClass = ''
                if(profileInfo.ownerID == r[i].DetailsID)
                    fromImageClass = ' changeprofpic_' + r[i].DetailsID;
                dvFeed.appendChild(new Element('a', { 'href': ('/' + r[i].WadjaID), 'class': 'imgFrom b_r ' + fromImageClass, 'html': '', 'styles': { 'background-image': 'url(' + r[i].Thumbnail + ')'} })); // From User Image
                dvFeed.appendChild(new Element('a', { 'href': ('/' + r[i].WadjaID), 'class': 'hrfFrom', 'html': r[i].Name })); // From User Name

                var wID = (r[i].Recipients.length > 0) ? (r[i].Recipients[0].DetailsID < 1 ? r[i].WadjaID : r[i].Recipients[0].WadjaID) : r[i].WadjaID; // To User

                //#Stopped: @argyris 
                //if (wID != r[i].WadjaID) // If to User not Self
                //    dvFeed.appendChild(new Element('a', { 'href': '/' + wID, 'class': 'hrfLabels', 'html': ('@' + wID) })); // show @recipient
                //-----------------------------------------------
                //#Handle feed links #u2,#pearl jam
                //#Stopped: #u2 #nike
                //-----------------------------------------------
                //var attachTitleLabelLinks = '#!My/';
                //if (profileInfo.viewerID != r[i].DetailsID)
                //attachTitleLabelLinks = '/' + r[i].WadjaID.toLowerCase();
                //else
                //attachTitleLabelLinks = '';
                //for (j = 0; j < r[i].Labels.length; j++) { //#Show Labels #Labels Links
                //dvFeed.appendChild(new Element('a', { 'href': attachTitleLabelLinks + '#!My/' + r[i].Labels[j].id + '/1', 'class': 'hrfLabels', 'html': ('#' + r[i].Labels[j].name) }));
                //}
                //-----------------------------------------------

                if (!isMessage || postToMessage)
                    dvFeed.appendChild(new Element('span', { 'html': '&nbsp;', 'styles': { 'display': 'block'} })); //#line break

                //#Remove label rule
                var removeLabel = false;
                //#Conversation pagelet:ismessage
                if (isMessage && !postToMessage) {

                    dvFeed.appendChild(new Element('span', { 'html': '&nbsp;', 'styles': { 'display': 'block'} })); //#line break
                    dvFeed.appendChild(new Element('img', { 'src': ('/s3.images/labels/feed_arrow' + (r[i].DetailsID == wProfile.Current.DetailsID ? "" : "_up") + '.png'), 'class': 'imgToArr' }));
                   
                    if (r[i].Recipients.length == 1) {// add recipient photo
                        var j = 0;
                        //for (var j = 0; j < r[i].Recipients.length; j++) {
                        var pic = (r[i].Recipients[j].DetailsID < 1 ? "" : r[i].Recipients[j].ImageURL.replace("_s.", "_n."));
                        if (pic != "")
                            dvFeed.appendChild(new Element('a', { 'href': ('/' + r[i].Recipients[j].WadjaID), 'class': 'imgTo b_r', 'html': '', 'styles': { 'background-image': 'url(' + pic + ')'} }));
                    }
                    

                    var temp_class = '';
                    var temp_delivery_counter = 0;
                    var temp_delivery_status = '';
                    var deliveryReportsBox = '';

                    for (var j = 0; j < r[i].Recipients.length; j++) {
                        if (r[i].Recipients.length == 1 && (r[i].isSMS)) {
                            if (r[i].Recipients[j].DeliveryStatus.length > 0)
                                temp_delivery_status = r[i].Recipients[j].DeliveryStatus;
                            else
                                temp_delivery_status = '';

                            temp_delivery_counter = 1;
                        }
                        else
                        {
                            temp_delivery_status = 'delivery reports ('+r[i].Recipients.length+')'
                            temp_delivery_counter = r[i].Recipients.length;
                        }

                        //#Build delivery reports box
                        if  (r[i].isSMS)
                        {
                            if (r[i].Recipients[j].DeliveryStatus!=null)
                            {
                                if (r[i].Recipients[j].DeliveryStatus.trim().toLowerCase()=='delivered')
                                    temp_class = 'blueColor';
                                else if (r[i].Recipients[j].DeliveryStatus.trim().toLowerCase()=='sending...')
                                    temp_class = 'greenColor';
                                else 
                                    temp_class = 'redColor';
                            }
                            deliveryReportsBox = deliveryReportsBox + '<div  class=\"deliveryInfo\">'+r[i].Recipients[j].Name+'<span class=\''+temp_class+'\'>'+ r[i].Recipients[j].DeliveryStatus+'</span></div>';
                            //?:deliveryReportsBox = deliveryReportsBox + "SMS sent to " + r[i].Recipients[j].Name + " &rarr; Status: " + r[i].Recipients[j].DeliveryStatus + "<br>";
                        }
                        //#Display recipients list
                        if (j<=3)
                            dvFeed.appendChild(new Element('a', { 'href': '/' + r[i].Recipients[j].WadjaID, 'class': 'hrfMessage', 'html':  r[i].Recipients[j].Name + ' ' })); 
                    }

                    //#SMS-attach delivery report
                    if (r[i].isSMS) {
                        dvFeed.appendChild(new Element('a', {'href': 'javascript:MyElement.toggleReveal("deliveryRp'+r[i].FeedID+'");', 'class': 'hrfMessage f_r cursor counterLabels', 'html': 'delivery reports ('+r[i].Recipients.length +')' }));
                        //#Delivery reports on the site
                        dvFeed.appendChild(new Element('div', { 'class': 'deliveryReportsDiv dnd', 'html': '<div><span class=\"f_l counterLabels\">'+temp_delivery_counter+'</span><span class=\"f_l\">delivery reports</span><span class="f_r closeIcon" onclick="MyElement.dissolve(\'deliveryRp'+r[i].FeedID+'\');">&nbsp;</span><div class=\"clearboth\"></div></div><div id=\"delivery_info\">'+deliveryReportsBox+'</div>', 'id':'deliveryRp'+r[i].FeedID})); 
                    }

                    //#Drop line
                    dvFeed.appendChild(new Element('span', { 'html': '&nbsp;', 'styles': { 'display': 'block'} }));
                }
                else if (r[i].Recipients.length > 0) { // If recipient count > 0 (message / notes)
                    var pic = (r[i].Recipients[0].DetailsID < 1 ? r[i].Thumbnail.replace("_n.", "_n.") : r[i].Recipients[0].ImageURL.replace("_s.", "_n."));
                    
                    // #remove label rule
                    // #if session alive-signed in
                    if (profileInfo.isLoggedIn) {
                        //#1.(check here)if (labels.id is equal to session.id) OR (labels.recipients.id is equal to session.id)
                        //#then profileInfo.ownerID
                        //#2.(check under attach label badge)if (labelbadge.ownerID_id is 0) or (labels.owner_id is equal session.id) 
                        //#then user can remove attach label badge
                        if ((profileInfo.viewerID == r[i].DetailsID) || (profileInfo.viewerID == r[i].Recipients[0].DetailsID))
                            removeLabel = true;

                        if (profileInfo.viewerID == r[i].Recipients[0].DetailsID)//if user in recipients
                            inRecipients = true;
                    }
                    else
                        removeLabel = false;

                    if (r[i].BaseLabelID == 2 && r[i].ConversationMessageCounter > 1) {
                        dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow_two.png', 'class': 'imgToArr lnkA', 'events': { 'click': (function (a) { return function () { if(!document.location.hash.Contains('#!inbox/')) { document.location.hash = '#!inbox/' + a.urlEncode(); } else { document.location.hash = ''; setTimeout("document.location.hash = '!inbox/" + a.urlEncode() + "';", 300);} } })(r[i].ConversationID)} }));
                    }
                    else {
                        dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow.png', 'class': 'imgToArr' }));
                    }
                    var toImageClass = ''
                    if(profileInfo.ownerID == r[i].Recipients[0].DetailsID)
                        toImageClass = ' changeprofpic_'+r[i].Recipients[0].DetailsID;
                    dvFeed.appendChild(new Element('a', { 'href': ('/' + wID), 'class': 'imgTo b_r' + toImageClass, 'html': '', 'styles': { 'background-image': 'url(' + pic + ')'} }));
                    if (r[i].BaseLabelID == 5 && !isFromSearch && r[i].ContactID !=0 && !r[i].ContactReal)
                        dvFeed.appendChild(new Element('span', {'id':'aEdit_'+r[i].FeedID,'class': 'hrfMessage f_r hrfDLR counterLabels lnk marR0', 'html': '<span onclick="javascript:MyElement.toggleReveal(\'contact_form_'+r[i].FeedID+'\');$(\'aEdit_'+r[i].FeedID+'\').addClass(\'dndD\');">Edit contact</span>' })); // show contact details
                    // disabled"if (wID != r[i].WadjaID) // If to User not Self
                    if (!isFromSearch && r[i].BaseLabelID != 2 && !(r[i].BaseLabelID == 5 && !r[i].ContactReal)) {
                        dvFeed.appendChild(new Element('a', { 'href': '/' + wID, 'class': 'dnb', 'html': ('@' + wID + ' ') })); // show @recipient     
                    }
                    else if(r[i].BaseLabelID == 5 && !r[i].ContactReal) {
                        dvFeed.appendChild(new Element('a', { 'href': ''+location.href+'', 'class': 'dnb', 'html': ('@' + wID + ' ') })); // show @recipient
                   }
                    else 
                    {       
                        //#SMS-Show delivery report
                        if (r[i].isSMS) {
                            var temp_class = '';
                            var temp_delivery_counter = 0;
                            var temp_delivery_status = '';
                            var deliveryReportsBox = '';

                            for (var j = 0; j < r[i].Recipients.length; j++) {
                                if (r[i].Recipients.length == 1 && (r[i].isSMS)) {
                                    if (r[i].Recipients[j].DeliveryStatus.length > 0)
                                        temp_delivery_status = r[i].Recipients[j].DeliveryStatus;
                                    else
                                        temp_delivery_status = '';

                                    temp_delivery_counter = 1;
                                }
                                else
                                {
                                    temp_delivery_status = 'delivery reports ('+r[i].Recipients.length+')'
                                    temp_delivery_counter = r[i].Recipients.length;
                                }

                                //#Build delivery reports box
                                if (r[i].Recipients[j].DeliveryStatus!=null)
                                {
                                    if (r[i].Recipients[j].DeliveryStatus.toLowerCase()=='delivered')
                                        temp_class = 'blueColor';
                                    else if (r[i].Recipients[j].DeliveryStatus.toLowerCase()=='sending...')
                                        temp_class = 'greenColor';
                                    else 
                                        temp_class = 'redColor';
                                }
                                deliveryReportsBox = deliveryReportsBox + '<div  class=\"deliveryInfo\">'+r[i].Recipients[j].Name+'<span class=\''+temp_class+'\'>'+ r[i].Recipients[j].DeliveryStatus+'</span></div>';
                                //?:deliveryReportsBox = deliveryReportsBox + "SMS sent to " + r[i].Recipients[j].Name + " &rarr; Status: " + r[i].Recipients[j].DeliveryStatus + "<br>";
                                if (j<=3)
                                    dvFeed.appendChild(new Element('a', { 'href': '/' + r[i].Recipients[j].WadjaID, 'class': 'hrfMessage', 'html': '+'+ r[i].Recipients[j].Name + ' ' })); // show @recipient
                            }
                            dvFeed.appendChild(new Element('a', {'href': 'javascript:MyElement.toggleReveal("deliveryRp'+r[i].FeedID+'");', 'class': 'hrfMessage f_r cursor hrfDLR counterLabels', 'html': 'delivery reports ('+r[i].Recipients.length+')' })); // show delivery report
                            //#Delivery reports on the site
                            dvFeed.appendChild(new Element('div', { 'class': 'deliveryReportsDiv dnd', 'html': '<div><span class=\"f_l counterLabels\">'+temp_delivery_counter+'</span><span class=\"f_l\">delivery reports</span><span class="f_r closeIcon" onclick="MyElement.dissolve(\'deliveryRp'+r[i].FeedID+'\');">&nbsp;</span><div class=\"clearboth\"></div></div><div id=\"delivery_info\">'+deliveryReportsBox+'</div>', 'id':'deliveryRp'+r[i].FeedID})); 
                            //?:dvFeed.appendChild(new Element('a', { 'class': 'hrfMessage f_r cursor', 'html': '<span onclick=\"javascript:$(\'deliveryRp\'+r[i].FeedID).removeClass(\'dnd\');\">'+temp_delivery_status+'</span>' })); // show delivery report
                        }
                        else
                        {
                            for (var j = 0; j < r[i].Recipients.length; j++) {
                            if(!isFromSearch)
                                 dvFeed.appendChild(new Element('a', { 'href': '/' + r[i].Recipients[j].WadjaID, 'class': 'hrfMessage', 'html': '@'+r[i].Recipients[j].WadjaID + ' ('+ r[i].Recipients[j].Name + ')' })); // show @recipient
                            else {
                            if (r[i].Recipients[j].WadjaID != null)
                            dvFeed.appendChild(new Element('a', { 'href': '/' + r[i].Recipients[j].WadjaID, 'class': 'hrfMessage', 'html': '@'+r[i].Recipients[j].WadjaID })); // show @recipient from search
                            else 
                            dvFeed.appendChild(new Element('a', { 'href': '/' + wID, 'class': 'hrfMessage', 'html': '@'+wID })); // show @recipient from search
                           }
                          }
                        }
                    }

                    if (r[i].BaseLabelID == 2)
                        dvFeed.appendChild(new Element('span', { 'html': '&nbsp;', 'styles': { 'display': 'block'} })); // Drop line 

                } // Third Party Recipient
                else if (r[i].ExternalUserProfileURL != null && r[i].ExternalUserThumbnailURL != null) {
                    dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow_up.png', 'class': 'imgToArr' }));
                    dvFeed.appendChild(new Element('a', { 'href': r[i].ExternalUserProfileURL, 'class': 'imgTo b_r', 'target': '_blank', 'html': '', 'styles': { 'background-image': 'url(' + r[i].ExternalUserThumbnailURL.replace("digg.jpg", "digg_s.jpg") + ')'} }));
                    // add sender name-url to profile
                    if (r[i].BaseTypeID == 13 && !isFromSearch)//#Twitter
                        dvFeed.appendChild(new Element('a', { 'href': r[i].ExternalUserProfileURL, 'class': 'dnb', 'target': '_blank', 'html': r[i].ExternalUserFullnameURL }));
                    else if (r[i].ExternalUserFullnameURL.length > 0 && !isFromSearch)
                        dvFeed.appendChild(new Element('a', { 'href': r[i].WebArticleURL, 'class': 'dnb', 'target': '_blank', 'html': r[i].ExternalUserFullnameURL }));
                    else if(isFromSearch)
                        dvFeed.appendChild(new Element('a', { 'href': r[i].ExternalUserProfileURL, 'class': 'hrfMessage', 'target': '_blank', 'html': r[i].ExternalUserFullnameURL }));

                } //#Youtube 
                else if (r[i].BaseLabelID == 13) {
                    dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow_up.png', 'class': 'imgToArr' }));
                    dvFeed.appendChild(new Element('a', { 'href': '#1', 'class': 'imgTo b_r', 'target': '_blank', 'html': '', 'styles': { 'background-image': 'url(/s3.images/labels/youtubeApi.png)'} }));
                } //#Photos
                else if (r[i].BaseLabelID == 11) {
                    dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow.png', 'class': 'imgToArr' }));
                } //Contacts from search
                else if (r[i].BaseLabelID == 5 && isFromSearch) {
                    dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow_up.png', 'class': 'imgToArr' }));
                    var toImageClass = ''
                    if(profileInfo.ownerID == r[i].Recipients[0].DetailsID)
                        toImageClass = ' changeprofpic_'+r[i].Recipients[0].DetailsID;
                    dvFeed.appendChild(new Element('a', { 'href': '#1', 'class': 'imgYuTb b_r f_l' + toImageClass, 'target': '_blank', 'html': '', 'styles': { 'background-image': 'url(' + r[i].Recipients[0].ImageURL + ')'} }));
                } //#Points
                else if (r[i].BaseTypeID == 21) {
                    dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow.png', 'class': 'imgToArr' }));
                    var toImageClass = ''
                    if(profileInfo.ownerID == r[i].Recipients[0].DetailsID)
                        toImageClass = ' changeprofpic_'+r[i].Recipients[0].DetailsID;
                    dvFeed.appendChild(new Element('a', { 'href': ('/' + wID), 'class': 'imgTo b_r' + toImageClass, 'html': '', 'styles': { 'background-image': 'url(' + r[i].Thumbnail + ')'} }));
                }
                else if (r[i].BaseLabelID == -1 && isFromSearch) {
                    dvFeed.appendChild(new Element('img', { 'src': '/s3.images/labels/feed_arrow_up.png', 'class': 'imgToArr' }));
                    dvFeed.appendChild(new Element('a', { 'href': '#1', 'class': 'imgTo b_r f_l', 'target': '_blank', 'html': '', 'styles': { 'background-image': 'url(/s3.images/labels/boss.png)'} }));
                }

                var spnTextClass = "spnText";

                if (r[i].BaseLabelID == 11 || (isMessage && !postToMessage) || r[i].BaseTypeID == 21) //photos - message - points:remove left margin
                    spnTextClass = "spnTextNomargin";
                else
                    spnTextClass = "spnText";

                if (isFromSearch)
                    dvFeed.appendChild(new Element('span', { 'html': '&nbsp;', 'styles': { 'display': 'block'} })); // Drop line 
                var textID;
                if (r[i].BaseLabelID == 5 && !isFromSearch && r[i].ContactID !=0 && !r[i].ContactReal)
                    textID = r[i].ContactID;
                else
                    textID = r[i].FeedID;
                dvFeed.appendChild(new Element('span', { 'id': ('spnText' + textID), 'class': spnTextClass, 'html': wProfile.Render.Body(r[i].Body.replaceAll("href=","target='_blank' href="), r[i].BaseTypeID, r[i].FeedID, isFromSearch), 'styles': {} })); // Body Text no word wrap
                // #attached-link,youtube,photos
                if (r[i].Attachment!=null && r[i].Attachment != '')
                {   
                    try 
                    {
                        var attInfo = JSON.decode(r[i].Attachment);
                        //#thumb
                        var att_embed = attInfo.embed;
                        var att_embedplay = '';

                        if (att_embed.trim().length >0)
                        {
                             att_embed = attInfo.embed;
                             att_embedplay = 'onclick=\"MyElement.dissolve(\'attach_thumb_'+r[i].FeedID+'\');MyElement.reveal(\'attach_embed_'+r[i].FeedID+'\');MyElement.reveal(\'feed_play_attach' + r[i].FeedID+'\');\"';
                            
                        }

                        if (attInfo.thumb.trim()!='')
                            dvFeed.appendChild(new Element('div', {'class':'f_l padT10','style':'margin-left: 120px','html':'<div id=\"attach_embed_'+r[i].FeedID+'\" class=\"dnd\">'+att_embed+'</div><table><tr><td id=\"attach_thumb_'+r[i].FeedID+'\"  style=\"vertical-align:top;\"><img class=\"cursor b_r\" '+att_embedplay+' style=\"width:100px;\" src=\"'+attInfo.thumb+'\"/></td><td style=\"vertical-align:top;word-wrap: break-word;font-size:11px;\"><table cellpadding=\"3\"  cellspacing=\"3\"><tr><td><a target=\"_blank\" href=\"'+attInfo.url+'\">'+attInfo.title.replaceAll('&quot;','\"').replaceAll('&#39;','\'')+ '</a></td></tr><tr><td> <a target=\"_blank\" href=\"'+attInfo.url+'\" class=\"grayColor f11\">'+attInfo.url+'</a></td></tr><tr><td>'+attInfo.description.replaceAll('&quot;','\"').replaceAll('&#39;','\'')  + '</td></tr></table></td></tr></table>'}));
                        else
                            dvFeed.appendChild(new Element('div', {'class':'f_l padT10','style':'margin-left: 120px','html':'<table cellpadding=\"3\"  cellspacing=\"3\" style=\"vertical-align:top;word-wrap: break-word;font-size:11px;\"><tr><td><a target=\"_blank\" href=\"'+attInfo.url+'\">'+attInfo.title.replaceAll('&quot;','\"').replaceAll('&#39;','\'')+ '</a></td></tr><tr><td> <a target=\"_blank\" href=\"'+attInfo.url+'\" class=\"grayColor f11\">'+attInfo.url+'</a></td></tr><tr><td>'+attInfo.description.replaceAll('&quot;','\"').replaceAll('&#39;','\'')  + '</td></tr></table></td></tr></table>'}));
    
                    }
                    catch(jError)
                    {
                        dvFeed.appendChild(new Element('div', {'html':'render attachments:'+jError + r[i].Attachment}));
                    }
                }
                dvFeed.appendChild(new Element('span', { 'class': 'spnDate' + ((isMessage && !postToMessage) ? ' f_l mtmt vam' : ''), 'html': wProfile.Render.DateDiff(r[i].Date) })); // Date (ago)
                
                if (r[i].BaseLabelID == 5 && !isFromSearch && r[i].ContactID !=0 && !r[i].ContactReal)
                {
                    var cid = r[i].ContactID;
                    var feedid = r[i].FeedID;
                    var contact_form = "";
                    contact_form += '<div class=\"share-arrow\">&nbsp;</div><div class=\"contact_form\"><div><span class=\"contact_info\">First name</span><input id=\"contact_firstname_'+r[i].ContactID+'\" type=\"text\" class=\"textBoxSmall\" /></div>';
                    contact_form +='<div><span class=\"contact_info\">Last name</span><input id=\"contact_lastname_'+r[i].ContactID+'\" type=\"text\" class=\"textBoxSmall\" /></div>';
                    contact_form +='<div><span class=\"contact_info\">Date of birth</span>';
                    contact_form +='<select class=\"select\" id=\"contact_day_'+cid+'\">';
                    for(var d=1;d<=31;d++)
                    {
                        contact_form+='<option value=\"' + d +'\">'+d+'</option>';
                    }
                    contact_form +='</select> ';
                    contact_form +='<select class=\"select\" id=\"contact_month_'+cid+'\">';
                    for(var m=1;m<=12;m++)
                    {
                        contact_form +='<option value=\"' + m +'\">'+m+'</option>';
                    }
                    contact_form +='</select> ';
                    contact_form +='<select class=\"select\" id=\"contact_year_'+cid+'\">';
                    var year = new Date().getFullYear();
                    for(var y=year;y>=year-101;y--)
                    {
                        contact_form +='<option value=\"' + y +'\">'+y+'</option>';
                    }
                    contact_form +='</select></div>';

                    contact_form +='<div><span class=\"contact_info\">Gender</span>';
                    contact_form +='<select class=\"select\" id=\"contact_gender_'+cid+'\">';
                    contact_form +='<option value=\"Male\">Male</option><option value=\"Female\">Female</option>';
                    contact_form +='</select></div>';
                    contact_form +='<div><span class=\"contact_info\">URL</span><input id=\"contact_url_'+cid+'\" type=\"text\" class=\"textBoxSmall\" value=\"http://\" /></div>';
                    contact_form +='<div><span class=\"contact_info\">Email</span><input id=\"contact_email_'+cid+'\" type=\"text\" class=\"textBoxSmall\" /></div>';
                    contact_form +='<div><span class=\"contact_info\">Mobile</span><input id=\"contact_mobile_'+cid+'\" type=\"text\" class=\"textBoxSmall\" /></div>';
                    contact_form +='<div><span class=\"contact_info\">&nbsp;</span><input type=\"button\" class=\"btn_submit\" value=\"Save\" onclick=\"Contact.Save('+cid+')\"/></div>';
                    contact_form +='<div class=\"close\"><span onclick="javascript:MyElement.toggleReveal(\'contact_form_'+r[i].FeedID+'\');$(\'aEdit_'+r[i].FeedID+'\').removeClass(\'dndD\');">Close <span class=\"closeIcon\">&nbsp;</span></span></div></div>';
                    dvFeed.appendChild(new Element('div', {'html':contact_form, 'id':'contact_form_'+feedid, 'class':'dnd'}));
                    wjxContacts.send('GetInfo', cid, 0, function (res) {
                        if(res.error != null) return;
                        var oRes = JSON.decode(res.value);
                        
                        if($('contact_firstname_'+oRes.DetailsID))
                            $('contact_firstname_'+oRes.DetailsID).value=oRes.FirstName;
                        if($('contact_lastname_'+oRes.DetailsID))
                            $('contact_lastname_'+oRes.DetailsID).value=oRes.LastName;
                        if($('contact_url_'+oRes.DetailsID))
                            $('contact_url_'+oRes.DetailsID).value=oRes.URL;
                        if($('contact_email_'+oRes.DetailsID))
                            $('contact_email_'+oRes.DetailsID).value=oRes.Email;
                        if($('contact_mobile_'+oRes.DetailsID))
                            $('contact_mobile_'+oRes.DetailsID).value=oRes.Number;

                        var s=oRes.Birthday;
                        
                        var m = s.match(/^\/Date\(([-+])?(\d+)([-+]\d\d)?(\d\d)\)\/$/);
                        var date = null;
                        if (m) {
                            var sign=1;
                            if(m[1] != undefined && m[1] == '-')
                                sign=-1;
                            var timestamp = m[2];
                            var timezone = 0;
                            if(m[3] == undefined || m[3] == '')
                                timestamp += m[4];
                            else
                                timezone = 3600000*m[3] + 60000*m[4]
                            //date = new Date(sign*timestamp + timezone).format('%B %d, %Y');
                            date = new Date(sign*timestamp + timezone);
                        }

                        var day=date.getDate();
                        var month=date.getMonth()+1;
                        var year=date.getFullYear();

                        for (var i = 0; i < $('contact_day_'+oRes.DetailsID).options.length; i++) {
                            if ($('contact_day_'+oRes.DetailsID).options[i].value == day) {
                                $('contact_day_'+oRes.DetailsID).options[i].selected = true;
                                //alert($('contact_day_'+oRes.DetailsID).options[i].value + '=' + day);
                                break;
                            }
                        }
                        for (var i = 0; i < $('contact_month_'+oRes.DetailsID).options.length; i++) {
                            if ($('contact_month_'+oRes.DetailsID).options[i].value == month) {
                                $('contact_month_'+oRes.DetailsID).options[i].selected = true;
                                //alert($('gs_values_month').options[i].value + '=' + BdayMonth);
                                break;
                            }
                        }
                        for (var i = 0; i < $('contact_year_'+oRes.DetailsID).options.length; i++) {
                            if ($('contact_year_'+oRes.DetailsID).options[i].value == year) {
                                $('contact_year_'+oRes.DetailsID).options[i].selected = true;
                                break;
                            }
                        }
                        for (var i = 0; i < $('contact_gender_'+oRes.DetailsID).options.length; i++) {
                            if ($('contact_gender_'+oRes.DetailsID).options[i].value.toLowerCase() == oRes.Gender.toLowerCase()) {
                                $('contact_gender_'+oRes.DetailsID).options[i].selected = true;
                                //alert($('gs_values_day').options[i].value + '=' + BdayDay);
                                break;
                            }
                        }
                        
                    });
                }
                
                if (r[i].Recipients.length == 0) {// no recipient
                    // #remove label rule
                    if (profileInfo.isLoggedIn) {
                        if (profileInfo.viewerID == r[i].DetailsID)
                            removeLabel = true;
                    }
                    else
                        removeLabel = false;
                }

                // #design label badge
                // #design attached labels
                if (r[i].Labels != null) {
                    for (j = 0; j < r[i].Labels.length; j++) {
                        wProfile.Helper.Labels[r[i].Labels[j].id] = r[i].Labels[j];

                        var attachRemoveButton = '';
                        var attachLoadLabelLink = '#!';

                        if (removeLabel) {
                            // 1.(check here)if (labels.id is equal to session.id) OR (labels.recipients.id is equal to session.id)
                            // then profileInfo.ownerID
                            // 2.(check under attach label badge)if (labelbadge.ownerID_id is 0) or (labels.owner_id is equal session.id) 
                            // then user can remove attach label badge
                            if (((r[i].Labels[j].Owner_ID == 0) || r[i].Labels[j].Owner_ID == profileInfo.viewerID) && !isFromSearch)
                                removeLabel = true;
                            else
                                removeLabel = false;
                        }

                        //Handle load label links
                        //(profileInfo.viewerID != r[i].DetailsID)
                        attachLoadLabelLink = "#!"; //(wProfile.Current.Category != 'My' ? '/' + r[i].WadjaID.toLowerCase() : '') + '#!';
                       

                        if (r[i].Labels[j].StyleID == 0) {
                            // #default labels design
                            // #tools
                            if (removeLabel)
                                attachRemoveButton = '<span tile="Remove label" class="" onclick="feedActions.remove(' + r[i].FeedID + ',' + r[i].Labels[j].id + ',\'' + r[i].Labels[j].name.replace("\'", "\\'") + '\');">x</span>';
                            if (j == 0) dvFeed.appendChild(new Element('span', { 'class': 'lblSpacer' }));

                            // # My, Follow, Every: wProfile.Current.Category
                            attachLoadLabelLink = '/' + r[i].Labels[j].OwnerWadjaID.toLowerCase() + '#!'; //3/8/2010
                             if (isFromSearch)
                            attachLoadLabelLink = '/' + r[i].WadjaID.toLowerCase() + '#!';
                            dvFeed.appendChild(new Element('span', { 'id': 'attachedlabel_' + r[i].FeedID + '_' + r[i].Labels[j].Owner_ID + '_' + r[i].Labels[j].id,'rel': r[i].Labels[j].name.replace("'", "\'"), 'class': 'lblBox b_r ' + r[i].Labels[j].style, 'html': '<a href="' + attachLoadLabelLink + 'My/' + r[i].Labels[j].id + '/1" class="b_r">' + r[i].Labels[j].name + '</a>' + attachRemoveButton }));
                        }
                        else // #custom label badges
                        {
                            // #share 
                            var attachShareButton = '';
                            var attachFollowersButton = '';
                            var attachFollowersCounter = '99+';
                            var attachLabelCustomIcon = '';
                            var attachCustomStyle = '';
                            var attachLabelName = r[i].Labels[j].name;

                            // #Custom button styles
                            if (r[i].Labels[j].thumbURL.length > 0)
                                attachCustomStyle = 'background-color:' + r[i].Labels[j].bgColor + ';color:' + r[i].Labels[j].fontColor + ' !important;';
                            else
                                attachCustomStyle = 'background-color:' + r[i].Labels[j].bgColor + ';color:' + r[i].Labels[j].fontColor + ' !important;padding:3px 5px !important;';

                            // #Remove button function
                            attachHoverStyle = '' + r[i].Labels[j].bgColor.replace("#", "");
                            if (removeLabel)
                                attachRemoveButton = '<span style="' + attachCustomStyle + '" tile="Remove label" onclick="feedActions.remove(' + r[i].FeedID + ',' + r[i].Labels[j].id + ',\'' + r[i].Labels[j].name.replace("\'", "\\'") + '\');" class="h_' + attachHoverStyle + '">x</span>';

                            // #Custom label icon
                            if (r[i].Labels[j].thumbURL.length > 0)
                                attachLabelCustomIcon = '<img height="14px" width="17px" class="cursor"  src="' + r[i].Labels[j].thumbURL + '" />';

                            // #followers
                            if (j == 0) dvFeed.appendChild(new Element('span', { 'class': 'lblSpacer' }));
                            dvFeed.appendChild(new Element('span', { 'id': 'attachedlabel_' + r[i].FeedID + '_' + r[i].DetailsID + '_' + r[i].Labels[j].id,'rel':r[i].Labels[j].name.replace("\'", "\\'"), 'class': 'lblBox b_r ' + r[i].Labels[j].style, 'html': '<a href="' + r[i].Labels[j].OwnerWadjaID.toLowerCase() + attachLoadLabelLink + 'My/' + r[i].Labels[j].id + '/1" class="h_' + attachHoverStyle + '" style="' + attachCustomStyle + '">' + attachLabelCustomIcon + attachLabelName + '</a>' + attachFollowersButton + attachShareButton + attachRemoveButton }));
                            //dvFeed.appendChild(new Element('span', { 'id': 'attachedlabel_' + r[i].FeedID + '_' + r[i].DetailsID + '_' + r[i].Labels[j].id, 'class': 'lblBox b_r ' + r[i].Labels[j].style, 'html': '<a href="' + attachLoadLabelLink + wProfile.Current.Category + '/' + r[i].Labels[j].id + '/1" class="h_' + attachHoverStyle + '" style="' + attachCustomStyle + '">' + attachLabelCustomIcon + attachLabelName + '</a>' + attachFollowersButton + attachShareButton + attachRemoveButton }));

                        }
                    }
                }

                // Apply Label / Print / Pin / Trash etc icons, bottom right
                // #Rules
                // Enable tools only when user singed in and he/she is the owner of the label
                // #Message: 	3  reply|forward|print|push-pin|star|trash|apply
                // #Youtube: 	14 push-pin|star|apply|trash
                // #Twitter: 	13 push-pin|star|apply|trash
                // #Photo: 		12 push-pin|set as profile|star|apply|trash
                // #Lastfm: 	28 push-pin|star|apply|trash
                // #Digg: 		27 push-pin|star|apply|trash
                // #Text: 		9  push-pin|star|apply|trash
                // #Credits: 	21 star|apply|trash
                // #Contact: 	6  edit|message|sms|star|apply|trash
                // #Trash:		4  restore?
                if (profileInfo.isLoggedIn && ((profileInfo.viewerID == r[i].DetailsID || inRecipients) || (isMessage && !postToMessage)) && r[i].BaseTypeID != -1) {

                    if ((!isMessage || postToMessage) && !isFromSearch) {
                        //apply label drop-down
                        var dvPlus = dvFeed.appendChild(new Element('a', { 'class': 'lblBox lblBoxApply b_r f_r', 'id': 'feed_pluslabel_' + r[i].FeedID + '', 'href': 'javascript:feedActions.plusLabel(' + r[i].FeedID + ');', 'title': 'Apply label on this feed' }));

                        dvPlus.appendChild(new Element('span', { 'class': 'cursor applyLabel', 'html': 'Label' }));
                        dvPlus.appendChild(new Element('span', { 'class': 'cursor applyLabelArrow', 'html': '&nbsp;</span>' }));
                        dvFeed.appendChild(dvPlus);
                        //var dvApply = new Element('span', { 'id': 'feed_apply_' + r[i].FeedID, 'class': 'dndD f_r applyBox', 'html': '<span onclick="feedActions.togglemylabels_dropdown(' + r[i].FeedID + ');">&nbsp;+&nbsp;</span>' }); // create a div container:.
                        //dvApply.appendChild(new Element('input', { 'id': 'feed_apply_box_' + r[i].FeedID, 'type': 'text', 'class': 'findBox feedapplyBox' }));

                        var dvApply = new Element('div', { 'id': 'feed_pluslabel_dropdown_' + r[i].FeedID, 'class': 'dndD dropdown f_r', 'html': '{drop-down}' }); // dndD create a div container:.
                        dvFeed.appendChild(dvApply);
                        //trash
                        if (wProfile.Current.LabelID == '3') { // already in Trash label
                            dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.deleteFeed(' + r[i].FeedID + ');', 'class': 'applyTrash f_r', 'html': '', 'title': 'Delete this feed' }));
                        }
                        else {
                            dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.trash(' + r[i].FeedID + ',3);', 'class': 'applyTrash f_r', 'html': '', 'title': 'Trash this feed' }));
                        }
                        
                        dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.star(' + r[i].FeedID + ',4,\'Starred\',\'lblStarred\');', 'class': 'applyStar f_r', 'html': '', 'title': 'Star this feed' }));
                        if(r[i].HasPushpin)
                            dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin('+r[i].FeedID+');', 'class': 'applyPin_on', 'html': '' ,'title':'Push pin on', 'id':'push_pin_'+r[i].FeedID}));
                        else
                            dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin('+r[i].FeedID+');', 'class': 'applyPin_off', 'html': '' ,'title':'Push pin off', 'id':'push_pin_'+r[i].FeedID}));

                        if (r[i].BaseLabelID == 2) {
                            dvFeed.appendChild(new Element('a', { 'events': { 'click': (function (a) { return function () { if(!document.location.hash.Contains('#!inbox/')) { document.location.hash = '#!inbox/' + a.urlEncode(); } else { document.location.hash = ''; setTimeout("document.location.hash = '!inbox/" + a.urlEncode() + "';", 300);} } })(r[i].ConversationID) }, 'class': 'openConv f_r', 'html': 'Open', 'title': 'Open conversation' }));
                        }
                        

                    }

                    // Message -
                    if (r[i].BaseTypeID == 3 && (isMessage && !postToMessage)) {
                        dvFeed.appendChild(new Element('a', { 'href': '/user/views/print.aspx?id=' + r[i].FeedID + '&subj=' + r[i].ConversationID, 'target': '_blank', 'class': 'applyPrint f_r', 'html': '', 'title': 'Print conversation' }));
                        dvFeed.appendChild(new Element('a', { 'href': 'javascript: void(0);', 'class': 'applyForward f_r', 'html': '', 'title': 'Forward', 'events': { 'click': (function (a) { return function () { feedActions.forward(a); } })(r[i].Body)} }));
                        dvFeed.appendChild(new Element('a', { 'href': 'javascript: void(0);', 'class': 'applyReply f_r', 'html': '', 'title': 'Reply feed', 'events': { 'click': (function (a) { return function () { feedActions.reply(a); } })(r[i])} }));
                        feedActions.reply(r[i]);
                    } // Youtube -
                    else if (r[i].BaseTypeID == 14) {
                        dvFeed.appendChild(new Element('span', { 'id': 'feed_play_' + r[i].FeedID, 'onclick': 'javascript:wProfile.Render.YouTubeClose(' + r[i].FeedID + ');', 'class': 'dndD f_r closePic', 'html': '&uarr; Close', 'title': 'Close Youtube video' }));
                        //dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin();', 'class': 'applyPin f_r', 'html': '' ,'title':'Push pin'}));
                    }
                   // Twitter -
                    else if (r[i].BaseTypeID == 13) {
                        //dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin();', 'class': 'applyPin f_r', 'html': '' ,'title':'Push pin'}));
                    } // Photo -
                    else if (r[i].BaseTypeID == 12) {
                        var getMediaID = r[i].Body.split('|'); //[0]: Image URL,[1]: Feed text, [2]: Media id                       
                        if(getMediaID[0] != r[i].Thumbnail.replace("http://photos.wadja.com/", "").replace("_n","_o"))
                        dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.setProfilepic(\'' + getMediaID[0] + '\',' + getMediaID[2] + ');', 'class': 'applyPic f_r padT2', 'html': '&nbsp;', 'title': 'Set as profile pic' }));
                        dvFeed.appendChild(new Element('a', { 'id': 'feed_view_' + r[i].FeedID, 'href': 'javascript:wProfile.Render.viewPhotoClose(' + r[i].FeedID + ');', 'class': 'f_r closePic dndD', 'html': '&uarr; Close', 'title': 'Close pic' }));
                        //dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin();', 'class': 'applyPin f_r', 'html': '' ,'title':'Push pin'}));
                    } // Lastfm -
                    else if (r[i].BaseTypeID == 28) {
                        //dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin();', 'class': 'applyPin f_r', 'html': '' ,'title':'Push pin'}));
                    } // Digg -
                    else if (r[i].BaseTypeID == 27) {
                        //dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin();', 'class': 'applyPin f_r', 'html': '' ,'title':'Push pin'}));
                    } // Notes -
                    else if (r[i].BaseTypeID == 9) {
                        //dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.pushPin();', 'class': 'applyPin f_r', 'html': '' ,'title':'Push pin'}));
                    } // Credits -
                    else if (r[i].BaseTypeID == 21) {

                    } // Contact -
                    else if (r[i].BaseTypeID == 6 && isFromSearch && profileInfo.viewerID != r[i].FeedID) {
                        dvFeed.appendChild(new Element('a', { 'id': 'addContact_' + r[i].FeedID, 'href': 'javascript:Contacts.AddFromSearch(\'' + r[i].WadjaID + '\',' + r[i].FeedID + ');', 'class': 'lblBoxApply lblBox b_r f_r dndD', 'html': '<span class=\"cursor applyLabel \">Contact</span><span class=\"cursor applyLabelContact\">&nbsp;</span>' ,'title':'Add contact'}));
                        wjxContacts.send('IfContact', r[i].FeedID, true, function(res) {
                            if(res.error != null) return;
                            var contactID = res.value.split('s@p@l@t')[1];
                            var oRes=JSON.decode(res.value.split('s@p@l@t')[0]);
                            if(oRes == false)
                                $('addContact_' + contactID).removeClass('dndD');
                        });                       
                    }
                    else if (r[i].BaseTypeID == 6 && !isFromSearch && !profileInfo.viewerID != r[i].FeedID)
                     dvFeed.appendChild(new Element('a', { 'href': 'javascript:feedActions.block_unblock('+r[i].FeedID+');', 'class': 'block_contact f_r', 'html': ' ', 'id':'block_unblock_' + r[i].FeedID}));
                }
                if (r[i].Attachment!=null) {
                    dvFeed.appendChild(new Element('a', { 'id': 'feed_play_attach' + r[i].FeedID, 'href': 'javascript:MyElement.dissolve(\'attach_embed_'+r[i].FeedID+'\');MyElement.reveal(\'attach_thumb_'+r[i].FeedID+'\');MyElement.dissolve(\'feed_play_attach' + r[i].FeedID+'\');', 'class': 'dnd f_r padR7 padT7', 'html': '&uarr; Close', 'title': 'Close Youtube video' }));
                   
                    } 
                

                frag.appendChild(dvFeed); // append to document fragment
                if (!isMessage) {
                    wProfile.Helper.Loaded.push(r[i].FeedID); // add to loaded feeds
                    wProfile.Current.MinID = Math.max(wProfile.Current.MinID, r[i].FeedID); // update min id (for new feeds)
                }
            }


            //No feeds-actions
            if (r.length == 0 && $('dvStream').get('html').length == 0 && !isFromSearch) {
                //check cookie as well
                var myCookie = Cookie.read("wj_news");

                if (myCookie == 'off')//turned off 
                {
                    $('noFeeds').addClass('dnd');
                    if('noFeeds_photo')
                    $('noFeeds_photo').addClass('dnd');
                    if('noFeeds_contacts')
                    $('noFeeds_contacts').addClass('dnd');
                    if('noFeeds_youtube')
                    $('noFeeds_youtube').addClass('dnd');
                    if('noFeeds_twitter')
                    $('noFeeds_twitter').addClass('dnd');
                    if('noFeeds_nomessage')
                    $('noFeeds_nomessage').addClass('dnd');
                    $('master_feeds_container').removeClass('dnd');
                }
                else if (myCookie != selectedLabelName) //turned off for all labels
                {
                    $('noFeeds').removeClass('dnd');
                    $('master_feeds_container').addClass('dnd');
                }
                else if (myCookie == null) //turned off-other than the above
                {
                    $('noFeeds').removeClass('dnd');
                    $('master_feeds_container').addClass('dnd');
                }
                // when viewing Trash label do not show noFeeds div
                if (wProfile.Current.LabelID == '3') {
                    $('noFeeds').addClass('dnd');
                }
                if (wProfile.Current.LabelID == '11' && profileInfo.profileBelongsToViewer) {
                    $('noFeeds').addClass('dnd');                    
                    if('noFeeds_contacts')
                    $('noFeeds_contacts').addClass('dnd');
                    if('noFeeds_youtube')
                    $('noFeeds_youtube').addClass('dnd');
                    if('noFeeds_twitter')
                    $('noFeeds_twitter').addClass('dnd');
                    if('noFeeds_nomessage')
                    $('noFeeds_nomessage').addClass('dnd');
                    
                    $('noFeeds_photo').removeClass('dnd');
                }
                if (wProfile.Current.LabelID == '5' && profileInfo.profileBelongsToViewer) {
                    $('noFeeds').addClass('dnd');
                    if('noFeeds_photo')
                    $('noFeeds_photo').addClass('dnd');                    
                    if('noFeeds_youtube')
                    $('noFeeds_youtube').addClass('dnd');
                    if('noFeeds_twitter')
                    $('noFeeds_twitter').addClass('dnd');
                    if('noFeeds_nomessage')
                    $('noFeeds_nomessage').addClass('dnd');
                   
                    $('noFeeds_contacts').removeClass('dnd');
                }
                if (wProfile.Current.LabelID == '13' && profileInfo.profileBelongsToViewer) {
                    $('noFeeds').addClass('dnd');
                    if('noFeeds_photo')
                    $('noFeeds_photo').addClass('dnd');
                    if('noFeeds_contacts')
                    $('noFeeds_contacts').addClass('dnd');                    
                    if('noFeeds_twitter')
                    $('noFeeds_twitter').addClass('dnd');
                    if('noFeeds_nomessage')
                    $('noFeeds_nomessage').addClass('dnd');
                    
                    $('noFeeds_youtube').removeClass('dnd');
                }
                if (wProfile.Current.LabelID == '12' && profileInfo.profileBelongsToViewer) {
                    $('noFeeds').addClass('dnd');
                    if('noFeeds_photo')
                    $('noFeeds_photo').addClass('dnd');
                    if('noFeeds_contacts')
                    $('noFeeds_contacts').addClass('dnd');
                    if('noFeeds_youtube')
                    $('noFeeds_youtube').addClass('dnd');                    
                    if('noFeeds_nomessage')
                    $('noFeeds_nomessage').addClass('dnd');
                   
                    $('noFeeds_twitter').removeClass('dnd');
                }
                 if (wProfile.Current.LabelID == '2' && !profileInfo.profileBelongsToViewer) {
                   $('noFeeds').addClass('dnd');
                    if('noFeeds_photo')
                    $('noFeeds_photo').addClass('dnd');
                    if('noFeeds_contacts')
                    $('noFeeds_contacts').addClass('dnd');
                    if('noFeeds_youtube')
                    $('noFeeds_youtube').addClass('dnd');
                    if('noFeeds_twitter')
                    $('noFeeds_twitter').addClass('dnd');
                                       
                    $('noFeeds_nomessage').removeClass('dnd');
                }
            }
            else {
                $('noFeeds').addClass('dnd');
                 if('noFeeds_photo')
                    $('noFeeds_photo').addClass('dnd');
                 if('noFeeds_contacts')
                    $('noFeeds_contacts').addClass('dnd');
                 if('noFeeds_youtube')
                    $('noFeeds_youtube').addClass('dnd');
                 if('noFeeds_twitter')
                    $('noFeeds_twitter').addClass('dnd');
                 if('noFeeds_nomessage')
                    $('noFeeds_nomessage').addClass('dnd');
                 if (!isFromSearch)
                    $('master_feeds_container').removeClass('dnd');
                 helpTooltips.Off();
            }

            try
            {
                if(!profileInfo.isLoggedIn) {
                    $('noFeeds').addClass('dnd');
                 if('noFeeds_photo')
                    $('noFeeds_photo').addClass('dnd');
                 if('noFeeds_contacts')
                    $('noFeeds_contacts').addClass('dnd'); 
                 if('noFeeds_youtube')
                    $('noFeeds_youtube').addClass('dnd'); 
                 if('noFeeds_twitter')
                    $('noFeeds_twitter').addClass('dnd'); 
                 if('noFeeds_nomessage')
                    $('noFeeds_nomessage').addClass('dnd'); 
}
            }
            catch(Error) { }

            if (isFromSearch) {
                //                $('master_feeds_container').addClass('dnd');
                //                $('search_feeds_container').removeClass('dnd');
                //                $('srch_feeds').empty();
                //                $('srch_labels').empty();
                //                $('srch_users').empty();
                //                $('srch_web').empty();
                switch (srch) {
                    case 'feeds':
                        $('srch_feeds').removeClass('dnd');
                        $('srch_feeds').appendChild(frag);
                        break;
                    case 'labels':
                        $('srch_labels').removeClass('dnd');
                        $('srch_labels').appendChild(frag);
                        break;
                    case 'people':
                        $('srch_users').removeClass('dnd');
                        $('srch_users').appendChild(frag);
                        break;
                    case 'web':
                        $('srch_web').removeClass('dnd');
                        $('srch_web').appendChild(frag);
                        break;
                    default:
                        break;
                }
            } else if (addTop) {
                try {
                    $('dvStream').insertBefore(frag, $('dvStream').childNodes[0]);
                }
                catch (err) { $('dvStream').appendChild(frag); }
            } else {

                $('dvStream').appendChild(frag); // Add to page

                //push new feeds every 15 sec!
                clearInterval(refTimer);
                refTimer = setInterval(function () {
                    if (pushstart == 0)
                        wProfile.GetNew();
                }, 15 * 1000);

                //show current label
                var selectedLabelID = parseInt(wProfile.Current.LabelID);

                if (selectedLabelID > 0 && wProfile.Helper.Labels.length > 0) {
                    // Change header link
                    if (wProfile.Helper.Labels[selectedLabelID] === undefined) {
                        wjxShhProfile.send('GetInfo', selectedLabelID, profileInfo.ownerID, function (r) {
                            if (r.error != null) {
                                return;
                            }
                            else {
                                r = JSON.decode(r.value);
                            }

                            //if (r.length == 0) return; //No feeds stop

                            wProfile.Helper.Labels[r.id] = r;

                            //                            if ($('txtBody')) {
                            //                                $('txtBody').value = '#' + wProfile.Helper.Labels[r.id].name; // Argyri: You can get label attributes like this!
                            //                                wjxShhProfile.send('WdjThnk', $('txtBody').value, wProfile.Compose.WadjaThinking);
                            //                            }
                            if ($('lblSignedOut'))
                                $('lblSignedOut').innerHTML = wProfile.Helper.Labels[r.id].name;
                            /*stopped: can be removed
                            if ($('HomeLabel')) {
                                $('HomeLabel').set('html', leftSide + wProfile.Helper.Labels[r.id].name);
                                $('HomeLabel').addClass('b_r pad3');
                                $('HomeLabel').highlight('#ddf', '#ccc');

                                selectedLabelName = wProfile.Helper.Labels[r.id].name;
                            }
                            */
                           
                        });
                    } 
                    else {
                        //                        if ($('txtBody')) {
                        //                            $('txtBody').value = '#' + wProfile.Helper.Labels[selectedLabelID].name; // Argyri: You can get label attributes like this!
                        //                            wjxShhProfile.send('WdjThnk', $('txtBody').value, wProfile.Compose.WadjaThinking);
                        //                        }

                        if ($('lblSignedOut'))
                            $('lblSignedOut').innerHTML = wProfile.Helper.Labels[selectedLabelID].name;

                        /*stopped: can be removed
                        if ($('HomeLabel')) {
                            $('HomeLabel').set('html', leftSide + wProfile.Helper.Labels[selectedLabelID].name);
                            $('HomeLabel').addClass('b_r pad3');
                            $('HomeLabel').highlight('#ddf', '#ccc');
                        }
                        */

                        //#When signed out-adding label name on user's info badge
                        if ($('guest_follow_current_label'))
                                $('guest_follow_current_label').set('html','#'+ wProfile.Helper.Labels[selectedLabelID].name);
                    }

                    // Trash all feeds under a specific label\
                    if (profileInfo.profileBelongsToViewer && (!isMessage || postToMessage)) {
                        var trashall_function = function () { feedActions.trashAll(selectedLabelID); }
                        var emptyTrash_function = function () { feedActions.emptyTrash(); }

                        $('dvFilters_trashall').removeEvents('click');
                        if (wProfile.Current.LabelID == '3') { // when viewing Trash label
                            $('dvFilters_trashall').addEvent('click', emptyTrash_function);
                            $('spnFilters_trashall').set('title', 'Delete forever');
                        }
                        else {
                            $('dvFilters_trashall').addEvent('click', trashall_function);
                            $('spnFilters_trashall').set('title', 'Move all feeds to trash');
                        }
                        
                        $('dvFilters_trashall').removeClass('dnd');
                        $('dvFilters').removeClass('dnd');
                    }
                    else {
                        $('dvFilters').addClass('dnd');
                        $('dvFilters_trashall').addClass('dnd');
                    }

                }
                else {
                    /// if returned to default labels-not under a specific label clear current label text-on top left
                    /*stopped:can be removed
                    if ($('HomeLabel')) {
                        if(!isMessage)
                            $('HomeLabel').set('html', '')
                        else {
                            $('HomeLabel').set('html', 'Message')
                            $('HomeLabel').addClass('b_r pad3');
                            $('HomeLabel').highlight('#ddf', '#ccc');
                        }
                    }
                    */
                }


                if (isMessage && !postToMessage) {
                    $('dvFilters').removeClass('dnd'); //
                    $('dvFilters_sender').addClass('dnd'); //hide from/to/to-from filters
                    $('dvFilters_trashall').addClass('dnd');
                    $('dvFilters_trashall').addClass('dnd');
                    $('dvBack').removeClass('dnd');
                } else {
                    $('dvBack').addClass('dnd');
                }
            }

            //reveal
            if (!isFromSearch) {
                $$('.feedMask').each(function (element, index) {
                    new Fx.Reveal($(element.get('id')), { duration: 750 }).reveal();
                });
                //#attach mouseover on all contact elements
                //#attach mouseover effect on all labels
                $$('.imgFrom').each(function (element, index) {
                    if (element.get('id')!=null)
                    {
                        var dummycontactel = $(element.get('id'));
                        dummycontactel.addEvent('mouseenter', function () {
                            alert('mouse-enter'+element.get('id'));
                        });
                        
                        dummycontactel.addEvent('mouseleave', function () {
                            alert('mouse-leave'+element.get('id'));
                        });
                    }
                });

                $$('.lblBox').each(function (element, index) {
                    if (element.get('id')!=null)
                    {
                        if ( element.get('id').indexOf('attachedlabel') >=0 )
                        {
                            var dummyel = $(element.get('id'));
                            //#attachedlabel_feedID_ownerID_labelID
                            var dummyel_split   = element.get('id').replace('attachedlabel_','').split('_');
                            var dummyel_feedID  = dummyel_split[0];
                            var dummyel_ownerID = dummyel_split[1];
                            var dummyel_labelID = dummyel_split[2];
                            var dummyel_pos     = dummyel.getCoordinates();
                            var dummyel_rel     = dummyel.get('rel');//#label name
                            //#hover craft stations-label
                            dummyel.addEvent('mouseenter', function () {
                                $('hovercraft-mass-content').removeClass('dnd');
                                launch_craft(element.get('id'),dummyel_labelID,dummyel_ownerID,dummyel_rel);
                                clearTimeout(hide_overlay);
                            });
                            
                            dummyel.addEvent('mouseleave', function () {
                                        hide_overlay = setTimeout(function () {
                                             craft_ui_reset();
                                        }, 650);
                            });
                            //#hover craft
                            $('hovercraft-mass-content').addEvent('mouseenter', function () {
                                clearTimeout(hide_overlay);
                            });
                            $('hovercraft-mass-content').addEvent('mouseleave', function () {
                                craft_ui_reset();
                            });

                            $('hovercraft-mass-content').addEvent('click', function () {
                                craft_ui_reset();
                            });
                            
                        }
                    }
                });
              
            }
            else {
                $('search_feeds_container').getElements('div.feedMask').each(function (element, index) {
                    //$(element.get('id')).removeClass('feedMask');
                    new Fx.Reveal($(element.get('id')), { duration: 750 }).reveal();
                });
            }

            //$('dvStream').style.width = ($('profileTHEME').getSize().x - 500) + 'px';
            if (!isFromSearch) {
                //Get label followers
                try {

                    InitLabelInfo(wProfile.Current.LabelID);
                }
                catch (Error) {
                    Notify.alert('Javascript error', '<div class="pad10">Javascript error while loading label followerd #' + Error + '. Label ID:' + wProfile.Current.LabelID + '</div>', 'Ok', 'red');
                }
            }
            //stop more-loading
            if ($('feeds_more_button')) {
                $('feeds_more_button').set('disabled', false);
                $('feeds_more_button').set('value', $('feeds_more_button').get('value').replace('...', ''));
            }
            //end of more-loading
        },
        Body: function (txt, type, fID, srch) {
            if (type == 14) return '<a href="javascript: wProfile.Render.YouTube(\'' + txt + '\', ' + fID + ');" class="imgYuTb b_r" title="Click to play youtube video" style="background-image: url(http://img.youtube.com/vi/' + txt + '/default.jpg);"><span class=\"youtube_play\">&nbsp;</span></a><div></div>';
            else if (type == 12) {//#Photos
                var splitText = txt.split('|'); //[0]: Image URL,[1]: Feed text,[2]: Media ID
                //return '<img src=\"/s3.images/labels/feed_arrow.png\" class=\"imgToArr f_l\"/><img src=\"/s3.images/share/upload_image.png\" class=\"f_l padL10 padR10\" height=\"30px\" width=\"30px\"/><a href="javascript: wProfile.Render.viewPhoto(\'' + txt + '\', ' + fID + ');" class="imgYuTb b_r f_l" style="background-image: url(http://photos.wadja.com/' + splitText[0].replace('_o.', '_n.') + ');"></a><span class=\"f_l padT10 padL10\">' + splitText[1] + '</span>';
                return '<a href="javascript: wProfile.Render.viewPhoto(\'' + txt.replaceAll("'","\\'").replaceAll("\"","\\'") + '\',\'' + type + '\', ' + fID + ');" class="imgYuTb b_r f_l marL5 marT5" style="background-image: url(http://photos.wadja.com/' + splitText[0].replace('_o.', '_n.') + ');"><span class=\"photo_play\">&nbsp;</span></a><span id="spnPhoto_caption_' + fID + '" class="f_l  padL10 padT5">' + wProfile.Render.Links(splitText[1].replaceAll("'","\'")) + '</span>';

            }
            else if (type == 9) return wProfile.Render.Links(txt);
            else if (type == 13) return wProfile.Render.Links(txt.replaceAll("&apos;", "\'")); //Tweets.Links
            else if (type == 28) return wProfile.Render.Links(txt); //LAST FM.Links
            else if (type == 27) return wProfile.Render.Links(txt); //DIGG.Links
            else if (type == 6) {//#Contacts
                var splitText = txt.split('|');
                var location = '&nbsp;-&nbsp;' + splitText[1];
                var name = splitText[0];
                var born = '&nbsp;-&nbsp;' + splitText[2];
                var email = splitText[3];
                if (email != null && email.length != 0)
                    return '<span class=\"f_l \">' + name + '</span> <span class=\"f_l \">' + born + '</span> <span class=\"f_l\">' + location + '</span><span class=\"f_l\">&nbsp;-&nbsp;<a href=\"' + email + '\" target=\"_blank\">' + email + '</a></span>';
                else
                    return '<span class=\"f_l \">' + name + '</span> <span class=\"f_l \">' + born + '</span> <span class=\"f_l\">' + location + '</span>';
            }
            else 
                return wProfile.Render.Links(txt);
            /*
            #For search
            if (type == -1 && srch) {
                var splitText = txt.split('|');
                var abstract = splitText[0];
                var DisplayURL = splitText[1];
                var ClickURL = splitText[2];
                return '<span class=\"f_l  padL10\">' + abstract + '</span><br/><a href=\"' + ClickURL + '\" class=\"f_l  padL10\">' + DisplayURL + '</a>';
            }*/
            return txt;
        },
        viewPhoto: function (txt, type, fID) {
            //if already opened
            if ($('spnText_viewer_' + fID)) {
                wProfile.Render.viewPhotoClose(fID);
                return;
            }
            //split text,image
            var splitFeed = txt.split('|');
            var htmlPhotoViewer = '<div id="vphoto_' + fID + '" ><img class="marT10 marL42 b_r" onClick="wProfile.Render.viewPhotoClose(' + fID + ');" title="Click photo to restore thumb view mode" class="cursor"  src="http://photos.wadja.com/' + splitFeed[0].replace("_o", "_d") + '"/><div class=\"padT10 marL42\">' + splitFeed[1] + '</div></div>';

            //Hide photo thumb
            $('spnText' + fID).appendChild(new Element('span', { 'id': 'spnText_viewer_' + fID, 'class': '', 'html': htmlPhotoViewer }));
            //hide photo text
            if ($('spnPhoto_caption_' + fID))
                $('spnPhoto_caption_' + fID).addClass('dnd');
            //show close link
            if ($('feed_view_' + fID))
                $('feed_view_' + fID).removeClass('dndD');

        },
        viewPhotoClose: function (fID) {
            if ($('spnText_viewer_' + fID))
                $('spnText_viewer_' + fID).destroy();
            //show photo text
            if ($('spnPhoto_caption_' + fID))
                $('spnPhoto_caption_' + fID).removeClass('dnd');
            if ($('feed_view_' + fID))
                $('feed_view_' + fID).addClass('dndD');
        },
        YouTube: function (ytID, fID) {
            //if already opened
            if ($('spnText_player_' + fID)) {
                wProfile.Render.YouTubeClose(fID);
                return;
            }
            //Hide video thumb
            $('spnText' + fID).appendChild(new Element('span', { 'id': 'spnText_player_' + fID, 'class': 'padL10 f_l padT3', 'html': '<object id="yvideo' + fID + '" width="440" height="285"><param name="movie" value="http://www.youtube.com/v/' + ytID + '&hl=en_US&fs=1"></param><param name="allowFullScreen" value="true"></param> <param name="wmode" value="opaque" /><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + ytID + '&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="440" height="285"  wmode="opaque"></embed></object>' }));
            //show close link
            if ($('feed_play_' + fID))
                $('feed_play_' + fID).toggleClass('dndD');
            //$('spnText' + fID).innerHTML = '<div class="loadingImage b_r"></div>';
        },
        YouTubeClose: function (fID) {
            if ($('spnText_player_' + fID))
                $('spnText_player_' + fID).destroy();
            if ($('feed_play_' + fID))
                $('feed_play_' + fID).toggleClass('dndD');
        },
        DateDiff: function (dt) {
            var dtNow = new Date();

            dt = new Date(parseInt(/\/Date\((\d+).*/.exec(dt)[1]));
            var oMinutes = Math.floor((dtNow.getTime() - dt.getTime()) / (1000 * 60));

            if (oMinutes <= 0) // fix error displaying -1
                return "just now";

            if (oMinutes >= (24 * 60 * 30))
                return Math.floor(oMinutes / (24 * 60 * 30)) + " month" + (Math.floor(oMinutes / (24 * 60 * 30)) == 1 ? "" : "s") + " ago";

            if (oMinutes >= (24 * 60))
                return Math.floor(oMinutes / (24 * 60)) + " day" + (Math.floor(oMinutes / (24 * 60)) == 1 ? "" : "s") + " ago";

            if (oMinutes >= 60)
                return Math.floor(oMinutes / 60) + " hour" + (Math.floor(oMinutes / 60) == 1 ? "" : "s") + " ago";

            return oMinutes + " minute(s) ago";
        },
        Links: function (s) {//MARK - URL parse
            if (s.indexOf('imgYouTube') > 0)
                return s; ///exclude feed content
            else {
                var initialString = s;
                var myregexp = /((((https?)|(ftps?)):\/\/)|(www.))[a-zA-Z0-9+&@#\/%=~\-_|$?!:.,\Z]+[.][a-zA-Z0-9+&@#\/%=~\-_|$?!:.,\Z]*[a-zA-Z0-9/]+/ig;
                var result = '';         // my match (valid url)

                var finalString = ''; //initialString;
                var temp = '';
                var startPoint = 0;
                var endPoint = 0;
                var tempString = '';
                var i = 0;

                while ((startPoint = initialString.indexOf('[artist]')) > -1) {
                    if ((endPoint = initialString.indexOf('[/artist]')) > -1) {
                        startPoint += '[artist]'.length;
                        tempString = initialString.substring(startPoint, endPoint);
                        tempString = tempString.replace(' ', '+');
                        //document.write(tempString + "<br/>");

                        initialString = initialString.replace('[artist]', '<a target=\"_blank\" href=\"http://www.last.fm/music/' + tempString + '\">');
                        initialString = initialString.replace('[/artist]', '</a>');
                    }
                    else
                        break;
                }

                while (initialString.indexOf('[url]') > -1)
                    initialString = initialString.replace('[url]', '  ');


                while ((startPoint = initialString.indexOf('[url=')) > -1) {
                    if (initialString.indexOf('[/url]') > -1 && (endPoint = initialString.indexOf(']')) > startPoint) {
                        startPoint += '[url='.length;
                        tempString = initialString.substring(startPoint, endPoint);
                        temp = tempString.substring(0, 4).toLowerCase(); // check if http exists at start of tempString, if not add it to the url

                        initialString = initialString.replace('[/url]', '</a>');
                        initialString = initialString.replace(']', '\">');

                        if (temp == 'http') {
                            initialString = initialString.replace('[url=', '<a target=\"_blank\" href=\"');
                        }
                        else {
                            initialString = initialString.replace('[url=', '<a target=\"_blank\" href=\"http://');
                        }
                    }
                    else
                        break;
                }


                var initialStringArray = initialString.split(' ');
                var finalStringArray = new Array();

                for (i = 0; i < initialStringArray.length; i++) {
                    //result = myregexp.exec(initialStringArray[i]); 
                    result = initialStringArray[i].match(myregexp);

                    if (result != null) {

                        temp = result[0].substring(0, 4).toLowerCase(); // check if http exists at start of result[0], if not add it to the url

                        startPoint = initialStringArray[i].indexOf(temp, 0);
                        tempString = initialStringArray[i].substring(startPoint - 6, startPoint);

                        if (tempString != 'href=\"') {
                            if (temp == 'http') {
                                finalStringArray[i] = initialStringArray[i].replace(result[0], '<a target=\"_blank\" href=\"' + result[0] + '\">' + result[0] + '</a>');
                            }
                            else {
                                finalStringArray[i] = initialStringArray[i].replace(result[0], '<a target=\"_blank\" href=\"http://' + result[0] + '\">' + result[0] + '</a>');
                            }
                        }
                        else
                            finalStringArray[i] = initialStringArray[i];
                    }
                    else
                        finalStringArray[i] = initialStringArray[i];

                    result = '';
                    temp = '';
                    tempString = '';
                }

                for (i = 0; i < finalStringArray.length; i++) {
                    finalString += finalStringArray[i];
                    finalString += ' ';
                }

                while (finalString.indexOf('[/url]') > -1)
                    finalString = finalString.replace('[/url]', '');


                // MARK-Return new link
                return finalString;
            }

        }
    },
    showNew: function () { // Show Feeds (after Send::Compose)
       
        wjxShhProfile.send('GetFeeds', this.Current.DetailsID, this.Current.Category, 0, this.Current.Filter, this.Current.Page, this.Current.MinID, function (r) {
            if (r.error != null) return;
            r = JSON.decode(r.value);
            if (r == "") return;

            for (i = 0; i < r.length; i++) {
                wProfile.Current.MinID = Math.max(wProfile.Current.MinID, r[i].FeedID); // update min id (for new feeds)
                wProfile.Helper.Pending.push(r[i]);
                wProfile.Helper.Loaded.push(r[i].FeedID);
            }
            new Fx.Reveal($('aNewFeeds'), { duration: 500 }).dissolve();
            new Fx.Reveal($('newfeeds_wrapper'), { duration: 500 }).dissolve();
            
            wProfile.Render.Start(wProfile.Helper.Pending, true);
        });
    },
    GetNew: function () { // Check for new feeds (yellow bar)
       
        if (window.location.hash.indexOf('!inbox') > 0) return;
        wjxShhProfile.send('GetFeeds', this.Current.DetailsID, this.Current.Category, this.Current.LabelID, this.Current.Filter, this.Current.Page, this.Current.MinID, function (r) {

            if (r.error != null) return;
            r = JSON.decode(r.value);
            if (!r) return;
            if (r == "") return;
            wProfile.Current.FeedsPending += r.length;
            for (i = 0; i < r.length; i++) {
                wProfile.Current.MinID = Math.max(wProfile.Current.MinID, r[i].FeedID); // update min id (for new feeds)
                wProfile.Helper.Pending.push(r[i]);
                wProfile.Helper.Loaded.push(r[i].FeedID);
            }


            /// Push new feeds
            if (($('aNewFeeds').getElement('span').innerHTML = wProfile.Helper.Pending.length) > 0) {
                new Fx.Reveal($('aNewFeeds'), { duration: 500 }).reveal();
                new Fx.Reveal($('newfeeds_wrapper'), { duration: 500 }).reveal();
                $('aNewFeeds_left_counter').set('html',wProfile.Helper.Pending.length);
            }
        });
        wProfile.InboxCounter();
       
    },
    InboxCounter: function () {
        var wjxCounter = new WADJAX('Profile', { statusBar: false });
        wjxCounter.send('InboxCounter', function (r) {
            if (r.error != null) return;
            r = JSON.decode(r.value);

            if (profileInfo.isLoggedIn)//#show message counter
            {
                if ($('message_wrapper'))
                {
                    if (r == 0) {
                        $('message_wrapper').addClass('dndD');
                    } else {
                        $('left_container_message_counter').innerHTML = r;
                        $('message_wrapper').removeClass('dndD');
                    }
                }
            }

            $$('.counter').each(function (el) {
                if (r == 0) {
                    el.addClass('dndD');
                } else {
                    el.innerHTML = r;
                    el.removeClass('dndD');
                }
            });
        });
    },
    Search: function (category, keyword) { // Search for people/feeds/labels/web

        wProfile.CurrentSearch.Keyword = keyword = keyword.replace('%20', '');
        if (category == '') category = 'feeds';
        wProfile.CurrentSearch.Category = category;
        wProfile.CurrentSearch.Page = 1;
        pushstart == 1; //stop push feeds
        $('srch_feeds').empty();
        $('srch_labels').empty();
        $('srch_users').empty();
        $('srch_web').empty();
        $('master_feeds_container').addClass('dnd');
        $('search_feeds_container').removeClass('dnd');
        $('dvsearchMore').removeClass('dnd');
        $('dvFilters_search').removeClass('dnd');
        $('filter_search_keyword').set('html', 'Curated real-time results for <span class=\"bolt\">' + wProfile.CurrentSearch.Keyword + '</span>'); //show result keyword
        
        if (category == '')
            wjxProfile.send('Search', keyword, category, wProfile.CurrentSearch.Page/*page*/, 3/*items_per_page*/, this.SearchAjaxCallBack);
        else
            wjxProfile.send('Search', keyword, category, wProfile.CurrentSearch.Page/*page*/, 10/*items_per_page*/, this.SearchAjaxCallBack);
       
    },
    SearchMore: function () {
        keyword = wProfile.CurrentSearch.Keyword.replace('%20', '');
        category = wProfile.CurrentSearch.Category;
        if ($('moreSearch_button')) {
                $('moreSearch_button').set('disabled', true);
                $('moreSearch_button').set('value', $('moreSearch_button').get('value') + '...');
        }
        if (category == '')
            wjxProfile.send('Search', keyword, category, wProfile.CurrentSearch.Page/*page*/, 3/*items_per_page*/, this.SearchAjaxCallBack);
        else
            wjxProfile.send('Search', keyword, category, wProfile.CurrentSearch.Page/*page*/, 10/*items_per_page*/, this.SearchAjaxCallBack);
    },
    SearchAjaxCallBack: function (r) {
        if ($('moreSearch_button')) {
                $('moreSearch_button').set('disabled', false);
                $('moreSearch_button').set('value', $('moreSearch_button').get('value').replace('...', ''));
        }
        if (r.error != null) return;
        r = JSON.decode(r.value);

        if ((wProfile.CurrentSearch.Category == 'feeds' && r.FeedList.length == 0) ||
            (wProfile.CurrentSearch.Category == 'labels' && r.LabelList.length == 0) || 
            (wProfile.CurrentSearch.Category == 'contacts' && r.UserList.length == 0)) {
            //no results text
            if((wProfile.CurrentSearch.Category == 'feeds' && $('srch_feeds').get('html') == '') ||
            (wProfile.CurrentSearch.Category == 'labels' && $('srch_labels').get('html') == '') || 
            (wProfile.CurrentSearch.Category == 'contacts' && $('srch_users').get('html') == '')) {
                $('srch_feeds').removeClass('dnd');
                $('srch_feeds').set('html', '<span class=\'f11 testShadow pad10\'>Can\'t find what you looking for. Try another keyword.</span>');
            }
            $('dvsearchMore').addClass('dnd');
            return;
            
        }
        wProfile.CurrentSearch.Page++;
        var category = searchCategory;
        $('master_feeds_container').addClass('dnd');
        $('search_feeds_container').removeClass('dnd');
        $('dvFilters_search').removeClass('dnd');
        $('dvsearchMore').removeClass('dnd');

        if (r.FeedList != null) { // Process FeedList
            wProfile.Render.Start(r.FeedList, false, 'feeds');
        }
        if (r.LabelList != null) { // Process LabelList
            wProfile.Render.Start(r.LabelList, false, 'labels');
        }
        if (r.UserList != null) { // Process UserList
            wProfile.Render.Start(r.UserList, false, 'people'); //TODO: Render.Start_RV should process user feeds
        }
        if (r.WebList != null) { // Process WebList
            wProfile.Render.Start(r.WebList, false, 'web'); //TODO: Render.Start_RV should process web results
        }
    },
    SetSearchType: function (oType) {
        this.Search.Type = oType;
    },
    Inbox: function (s) {
        
        wjxProfile.send('Inbox', s.urlDecode(), wProfile.Render.Start);
    },
    Load: function (oDetailsID, oCategory, oLabelID, oPage, resetFeeds) { // Load feeds (page_load / clicke label)

        this.Current.DetailsID = oDetailsID;
        this.Current.Category = oCategory;
        this.Current.LabelID = oLabelID;
        this.Current.Page = parseInt(oPage);

        if (profileInfo.ownerWadjaID == 'wadja')
        {
            /*//#if guest-posting
            if (getQuerystring('labelname') != '' && getQuerystring('post') != '')
            {}
            else*/
                this.Current.Category = 'Every';
        }
        if ($('EmbedFeed_text'))
            $('EmbedFeed_text').set('value', '<iframe name=\"I1\" frameborder=\"0\" allowtransparency=\"true\" scrolling=\"no\" style=\"border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; width: 300px; height: 560px; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; border-width: initial; border-color: initial;\" src=\"http://www.wadja.com/user/connect.aspx?wadjaid=' + profileInfo.ownerWadjaID + '&label=' + oLabelID.toString().replace('0', '8') + '\" id=\"I1\"></iframe>');
        
        //#Reset filters everytime we change label
        if (PreLabelID ==-1) //#first time
            PreLabelID = oLabelID;
        
        if (PreLabelID != oLabelID)
        {
            PreLabelID = oLabelID;
            jsHelper.resetFilters();
        }
        //-end of reset filters rule

        if (resetFeeds) {
            this.Current.MinID = 0;
            this.Helper.Loaded = [];
            this.Helper.Pending = [];
            this.Current.FeedsPending = 0;
            this.Current.filter = 0;
            pushstart == 0; //start push feeds
        }


        // if (oPage > 1) {
        //        this.Current.MinID = 0;
        // }
        //Clear search results

        $('srch_feeds').empty();
        $('srch_labels').empty();
        $('srch_users').empty();
        $('srch_web').empty();
        $('master_feeds_container').removeClass('dnd');
        $('search_feeds_container').addClass('dnd');
        $('dvFilters_search').addClass('dnd');

        //setTxtBodyText();
        //#Get label feeds-here
        if (pushstart == 0)
        {   
             //#debug:calculate loading time beforeload = (new Date()).getTime();
             wjxProfile.send('GetFeeds', this.Current.DetailsID, this.Current.Category, this.Current.LabelID, this.Current.Filter, this.Current.Page, 0, wProfile.Render.Start);
        }
    }
}

//#Feeds actions
var feedActions = {
    NewLabel: function (labelName) {
        return labelName;
    },
    LabelFilter: function (filterID) {
    
        if (filterID == '0')
            $('privacyicon_1').set('class', 'tofromImageDr');
        else if (filterID == '1')
            $('privacyicon_1').set('class', 'fromImageDr');
        else if (filterID == '2')
            $('privacyicon_1').set('class', 'toImageDr');

        //
        wProfile.Current.Filter = filterID;
        wProfile.Helper.Loaded = [];
        wProfile.Helper.Pending = [];
        wProfile.Current.FeedsPending = 0;

        wProfile.Load(wProfile.Current.DetailsID, wProfile.Current.Category, wProfile.Current.LabelID, wProfile.Current.Page, false);
        //
    },
    plusLabel: function (feedID) {

        var plsButton = $('feed_pluslabel_' + feedID);
        var plsDropdown = $('feed_pluslabel_dropdown_' + feedID);

        plsDropdown.toggleClass('dndD');


        //-draw dropdown
        currentDropdown = 'feed_pluslabel_dropdown_' + feedID; //so it can be closed

        //#Start dropdown
        var plsHTML;        
        var plsHTML_div = new Element('div', { 'class': ' ddlMenuTop ddlsProfile applyDropDown', 'id': 'ApplyDropdown' });
        var plsHTML_div_div = new Element('div', { 'class': 'dropLines' });
        var plsHTML_ul_auto = new Element('ul', { 'class': 'sub shadow', 'html': '<li><div><input type="text" id="feed_pluslabel_auto_' + feedID + '" autocomplete="off" maxlength="30" /></div></li>' });
        var plsHTML_ul_new = new Element('ul', { 'id': 'feed_pluslabel_new_wrapper_' + feedID, 'class': 'sub ulBtmNew dnd', 'html': '<li class="lidrop"><div id="feed_pluslabel_new_' + feedID + '" class="subdropNew bolt cursor" onclick="NewLabelWindow(this.id,' + feedID + ');">(create new)</div></li>' });
        var plsHTML_ul_value = new Element('ul', { 'class': 'sub ulLblApply', 'id': 'ulLblApply_' + feedID });

    
        rPls = JSON.decode(jsHelper.cachedData.My);
        //{"Count":0,"Digg":true,"LastFM":true,"OwnerWadjaID":"argyris","Owner_ID":71,"RoomID":163,"StyleID":0,"Twitter":true,"YouTube":true,"bgColor":"","bgImageURL":"","emailNotification":false,"feedCount":0,"followersCount":0,"fontColor":"","fontFamily":"","id":1144,"isLocation":false,"isSystem":false,"name":"A1","privacy":4,"style":"","thumbURL":"","type":1}
        for (i = 0; i < rPls.length; i++) {
            var labelStyle = '';
            if (rPls[i].StyleID > 0) {
                if (rPls[i].bgColor.length > 0)
                    labelStyle = labelStyle + 'background-color:' + rPls[i].bgColor;

                if (rPls[i].bgImageURL.length > 0)
                    labelStyle = labelStyle + ';background-url:(' + rPls[i].bgImageURL + ')';

                if (rPls[i].fontColor.length > 0)
                    labelStyle = labelStyle + ';color:' + rPls[i].fontColor + ' !important';

                if (rPls[i].fontFamily.length > 0)
                    labelStyle = labelStyle + ';font-family:' + rPls[i].fontFamily;
            }
            plsHTML_ul_value.appendChild(new Element('li', { 'html': '<a href=\'javascript:feedActions.plusLabel_apply("' + feedID + '","' + rPls[i].labelID + '","' + rPls[i].labelName + '","' + labelStyle + '","' + rPls[i].thumbURL + '","' + rPls[i].followersCount + '");\'>' + rPls[i].labelName + '</a>' }));
        } //for loop-end
              
        
        plsHTML_div_div.appendChild(plsHTML_ul_auto);       
        plsHTML_div_div.appendChild(plsHTML_ul_new);
        plsHTML_div_div.appendChild(plsHTML_ul_value);
        plsHTML_div.appendChild(plsHTML_div_div);

        plsDropdown.empty(); //empty before redrawing
        plsDropdown.appendChild(plsHTML_div);
        //#end dropdown
        //feed_pluslabel_auto_' + feedID

        //-attach autocomplete-meio
    
        var tempData = JSON.decode(jsHelper.cachedData.My);
        new Meio.Autocomplete.Select($('feed_pluslabel_auto_' + feedID), tempData, {
            selectOnTab: false, 	//
            minChars: 0,  			// The minimum number of characters the user has to input before the list of options to select is shown. 
            maxVisibleItems: 10,    // Defines the height of the list. If its 10 the list will have its height adjusted to show 10 options, but you can scroll to the other of course.
            onSelect: function (elements, value) {
                $('feed_pluslabel_auto_' + feedID).value = '';
                $('ulLblApply_' + feedID).removeClass('dnd');
                //hide drop down
                //load feeds
                //apply label
                feedActions.plusLabel_apply(feedID, value.labelID, value.labelName, '', value.thumbURL, value.followersCount);

                if ($('feed_pluslabel_new_wrapper_' + feedID))
                    $('feed_pluslabel_new_wrapper_' + feedID).addClass('dnd');

            }, // this event is fired when you select an option 
            onDeselect: function (elements) {
                $('ulLblApply_' + feedID).removeClass('dnd');
            }, // this event is fired when you deselect an option
            onNoItemToList: function (elements) {
                $('ulLblApply_' + feedID).addClass('dnd');
                if ($('feed_pluslabel_new_wrapper_' + feedID)) {
                    $('feed_pluslabel_new_wrapper_' + feedID).removeClass('dnd');
                    $('feed_pluslabel_new_' + feedID).set('html', '' + $('feed_pluslabel_auto_' + feedID).get('value') + ' (create new) ');
                }
            },
            filter: {
                type: 'contains',
                path: 'labelName'
            }
        }, autocompleteValues);

    },
    plusLabel_apply: function (feedID, labelID, labelName, labelStyle, labelIcon, labelFollowers) {
        //feedActions.plusLabel(feedID);
        feedActions.apply(feedID, labelID, labelName, labelStyle, labelIcon, labelFollowers);
    },
    apply: function (feedID, labelID, labelName, labelStyle, labelIcon, labelFollowers) {
        wjxLabel.send('Apply', feedID, labelID, function (res) {
            Notify.spinnerOff('Label applied', 1);
            if (!res.error) {
                var r = JSON.decode(res.value);
                if (!r) {
                    Notify.topBarOn('You can\'t have the same label twice. Please try another one.', 'red', 6)
                }
                else {
                    var dvFeedTemp = $('feed_' + feedID);
                    //followers
                    //icon
                    dvFeedTemp.appendChild(new Element('span', { 'id': 'attachedlabel_' + feedID + '_' + profileInfo.viewerID + '_' + labelID,'rel':labelName.replace("\'", "\\'"), 'class': 'lblBox b_r ' + labelStyle, 'html': '<a href="#!' + wProfile.Current.Category + '/' + labelID + '/1" class="b_r">' + labelName + '</a> <span tile="Remove label" class="" onclick="feedActions.remove(' + feedID + ',' + labelID + ',\'' + labelName.replace("'", "\'") + '\');">x</span>', 'style': labelStyle }));
                }
            }
            else {
                Notify.alert('Javascript error', '<p class=\'pad5\'>Javascript error while [apply label #' + Error + '</p>', 'Ok', 'red');
            }
        });
    },
    remove: function (feedID, labelID, labelName) {// remove attached label
        var alertBox = new Facebox({
            title: 'Remove label',
            message: '<div class=\'pad10\'>Are you sure you want to remove the label #' + labelName + ' from this feed?  </div>',
            cancelValue: 'Cancel',
            submitFunction: function () {
                // AJAX Request -
                wjxLabel.send('Remove', feedID, labelID, function (res) {
                    Notify.spinnerOff('Label "#' + labelName + '" has been removed.', 1);
                    if (!res.error) {
                        if ($('attachedlabel_' + feedID + '_' + profileInfo.viewerID + '_' + labelID)) {
                            //if feed's label is equal to the current label's feed then remove feed
                            if (wProfile.Current.LabelID == labelID) {
                                //remove with transition
                                Notify.remove('feed_' + feedID, 1);
                                (function () {
                                    //destroy element
                                    $('feed_' + feedID).destroy();
                                }).delay(5 * 1000);
                            }
                            else {// just remove the label badge
                                //remove with transition
                                MyElement.dissolve($('attachedlabel_' + feedID + '_' + profileInfo.viewerID + '_' + labelID));
                                //destrot element
                                $('attachedlabel_' + feedID + '_' + profileInfo.viewerID + '_' + labelID).destroy();
                            }
                        }
                    }
                    else {
                        Notify.alert('Javascript error', '<div class=\'pad10\'>Javascript error while [remove label] #' + Error + '</div>', 'Ok', 'red');
                    }
                });

                alertBox.close();
            },
            //ajaxErrorMessage: message to display when an ajax error occurs.
            //ajaxDelay: minimum time to display the loading message. (In milliseconds. Defaults to 0)
            submitValue: 'Yes',
            submitFocus: 'No'//If true, the submit button will be focused. (Pressing enter will activate it)
        });
        alertBox.show();
    },
    trashAll: function (labelId) {
        var alertBox = new Facebox({
            title: 'Move feeds to trash',
            message: '<div class=\'pad10\'>All feeds will be moved to the label #trash. Are you sure you want to continue? </div>',
            cancelValue: 'Cancel',
            submitFunction: function () {
                // AJAX Request -
                wjxLabel.send('DeleteAll', labelId, function (res) {
                    Notify.spinnerOff('All feeds ', 1);
                    if (!res.error) {
                        Notify.remove('dvStream', 1);
                        (function () {
                            $('dvStream').empty();
                        }).delay(5 * 1000);
                    }
                    else {
                        Notify.alert('Javascript error', '<p class=\'pad5\'>Javascript error while [trash all label\'s feeds] #' + Error + '</p>', 'Ok', 'red');
                    }
                });
                // end of AJAX
                alertBox.close();
            },
            //ajaxErrorMessage: message to display when an ajax error occurs.
            //ajaxDelay: minimum time to display the loading message. (In milliseconds. Defaults to 0)
            submitValue: 'Yes',
            submitFocus: 'No'//If true, the submit button will be focused. (Pressing enter will activate it)
        });
        alertBox.show();

    },
    emptyTrash: function () {
        var alertBox = new Facebox({
            title: 'Delete forever',
            message: '<div class=\'pad10\'>All feeds will be deleted forever. Are you sure you want to continue? </div>',
            cancelValue: 'Cancel',
            submitFunction: function () {
                // AJAX Request -
                wjxLabel.send('EmptyTrash', function (res) {
                    Notify.spinnerOff('All feeds ', 1);
                    if (!res.error) {
                        Notify.remove('dvStream', 1);
                        (function () {
                            $('dvStream').empty();
                        }).delay(5 * 1000);
                    }
                    else {
                        Notify.alert('Javascript error', '<p class=\'pad5\'>Javascript error while [empty trash] #' + Error + '</p>', 'Ok', 'red');
                    }
                });
                // end of AJAX
                alertBox.close();
            },
            //ajaxErrorMessage: message to display when an ajax error occurs.
            //ajaxDelay: minimum time to display the loading message. (In milliseconds. Defaults to 0)
            submitValue: 'Yes',
            submitFocus: 'No'//If true, the submit button will be focused. (Pressing enter will activate it)
        });
        alertBox.show();

    }, // trash feeds
    trash: function (feedID, labelID) {
        var alertBox = new Facebox({
            title: 'Move feed to trash',
            message: '<div class=\'pad10\'>Are you sure you want to move this feed to the label #trash? </div>',
            cancelValue: 'Cancel',
            submitFunction: function () {
                // AJAX Request -
                wjxLabel.send('Apply', feedID, labelID, function (res) {
                    Notify.spinnerOff('The feed has been moved to the trash.', 5);
                    if (!res.error) {
                        if ($('feed_' + feedID)) {
                            Notify.remove('feed_' + feedID, 1);

                            (function () {
                                //destrot element
                                $('feed_' + feedID).destroy();
                            }).delay(5 * 1000);
                        }
                    }
                    else {
                        Notify.alert('Javascript error', '<p class=\'pad5\'>Javascript error while [trash feed] #' + Error + '</p>', 'Ok', 'red');
                    }
                });
                // end of AJAX
                alertBox.close();
            },
            //ajaxErrorMessage: message to display when an ajax error occurs.
            //ajaxDelay: minimum time to display the loading message. (In milliseconds. Defaults to 0)
            submitValue: 'Yes',
            submitFocus: 'No'//If true, the submit button will be focused. (Pressing enter will activate it)
        });
        alertBox.show();

    },
    deleteFeed: function (feedID) {
        var alertBox = new Facebox({
            title: 'Delete feed forever',
            message: '<div class=\'pad10\'>Are you sure you want to delete this feed forever? </div>',
            cancelValue: 'Cancel',
            submitFunction: function () {
                // AJAX Request -
                wjxLabel.send('DeleteFeed', feedID, function (res) {
                    Notify.spinnerOff('The feed has been permanently deleted.', 5);
                    if (!res.error) {
                        if ($('feed_' + feedID)) {
                            Notify.remove('feed_' + feedID, 1);

                            (function () {
                                //destroy element
                                $('feed_' + feedID).destroy();
                            }).delay(5 * 1000);
                        }
                    }
                    else {
                        Notify.alert('Javascript error', '<p class=\'pad5\'>Javascript error while [delete feed] #' + Error + '</p>', 'Ok', 'red');
                    }
                });
                // end of AJAX
                alertBox.close();
            },
            //ajaxErrorMessage: message to display when an ajax error occurs.
            //ajaxDelay: minimum time to display the loading message. (In milliseconds. Defaults to 0)
            submitValue: 'Yes',
            submitFocus: 'No'//If true, the submit button will be focused. (Pressing enter will activate it)
        });
        alertBox.show();

    },
    star: function (feedID, labelID, labelName, labelStyle) {
        wjxLabel.send('Apply', feedID, labelID, function (res) {
            Notify.spinnerOff('done', 1);
            if (!res.error) {
                // attach star label 

                var r = JSON.decode(res.value);

                if (!r) {
                    Notify.topBarOn('You can\'t have the same label twice. Please try another one.', 'red', 6)
                }
                else {
                    var dvFeedTemp = $('feed_' + feedID);
                    dvFeedTemp.appendChild(new Element('span', { 'id': 'attachedlabel_' + feedID + '_' + profileInfo.viewerID + '_' + labelID,'rel':labelName.replace("'", "\'"), 'class': 'lblBox b_r ' + labelStyle, 'html': '<a href="#!' + wProfile.Current.Category + '/' + labelID + '/1" class="b_r">' + labelName + '</a> <span tile="Remove label" class="" onclick="feedActions.remove(' + feedID + ',' + labelID + ',\'' + labelName.replace("'", "\'") + '\');">x</span>' }));
                }
            }
            else {
                Notify.alert('Javascript error', '<p class=\'pad5\'>Javascript error while [star label feed] #' + Error + '</p>', 'Ok', 'red');
            }
        });
    },
    pushPin: function (feedid) {
        var value=false;
        if($('push_pin_'+feedid).className == 'applyPin_on'){
           //$('push_pin_'+feedid).removeClass('applyPin_on');
           //$('push_pin_'+feedid).addClass('applyPin_off');
            value=false;
        }
        else
        {
           //$('push_pin_'+feedid).removeClass('applyPin_off');
           //$('push_pin_'+feedid).addClass('applyPin_on');
           value=true;
        }
        var wadjax_Labels = new WADJAX('Labels', { statusBar: false });
        wadjax_Labels.send('UpdatePushpin', feedid, value, function(res) {
            if(res.error != null) return;
            if(res.value == '1')
            {
                if(!value) {
                    $('push_pin_'+feedid).removeClass('applyPin_on');
                    $('push_pin_'+feedid).addClass('applyPin_off');
                }
                else {
                    Notify.topBarOn('Feed is archived', '', 4)
                    $('push_pin_'+feedid).removeClass('applyPin_off');
                    $('push_pin_'+feedid).addClass('applyPin_on');
                }
            }

        });
    },
    block_unblock: function (feedid) {
      if($('block_unblock_'+feedid).hasClass('block_contact'))
        {
            $('block_unblock_'+feedid).addClass('unblock_contact');
            $('block_unblock_'+feedid).removeClass('block_contact');
        }
        else
        {
            $('block_unblock_'+feedid).addClass('block_contact');
            $('block_unblock_'+feedid).removeClass('unblock_contact');
        }
    },
    setProfilepic: function (mediaURL, mediaID) {
        try {

            Notify.spinnerOn('loading...', 'still loading', 5);

            oWUser.send('UpdateProfileImage', mediaID, function (res) {
                $('profile_pic').set('src', 'http://photos.wadja.com/' + mediaURL);
                $('contact_name_over').set('src', 'http://photos.wadja.com/' + mediaURL.replace('_o.','_t.'));
                $('navigation1_detailsProfilepic').set('src', 'http://photos.wadja.com/' + mediaURL.replace('_o.','_t.'));
                $$('.changeprofpic_'+profileInfo.ownerID).each(function (element, index) {
                    var photoPath = 'url("http://photos.wadja.com/'+ mediaURL.replace('_o.','_n.')+'")';
                    element.setStyle('background-image', photoPath);
                });
                Notify.spinnerOff('Done', 5);
            });
        }
        catch (Error) {
            Notify.alert('Javascript error', '<p class=\'pad5\'>Javascript error [function:setProfilepic] #' + Error + '</p>', 'Ok', 'red');
        }
    },
    reply: function (feed) {
        //$('txtBody').value = '';
        var text = '';
        if (profileInfo.viewerID != feed.DetailsID)
            text = '@' + feed.WadjaID;
            //$('txtBody').value = '@' + feed.WadjaID;

        for (var i = 0; i < feed.Recipients.length; i++) {
            if (feed.Recipients[i].DetailsID != profileInfo.viewerID)
                text += ' ' + feed.Recipients[i].Name;
                //$('txtBody').value += ' ' + feed.Recipients[i].Name;
        }

//        while ($('txtBody').value.indexOf(' ') == 0) {
//            $('txtBody').value = $('txtBody').value.substring(1);
//        }
        while (text.indexOf(' ') == 0) {
            text = text.substring(1);
        }
        text += ' ';
        //$('txtBody').value += ' ';
        //$('txtBody').focus();
        SetTextBox(text);
    },
    forward: function (txt) {
        if($('txtBody')) {
            $('txtBody').removeClass('type_message');
            $('txtBody').value = "\n----- Forwarded Text -----\n" + txt;
        }
    },
    print: function () {
        //
    }
}

/// #Privacy-functions
function ChangePrivacy(NewPrivacyID) {
    LabelPrivacyIcon(NewPrivacyID);

    try {
        var oWadjaX = new WADJAX('labels', { statusBar: false });
        Notify.spinnerOn('loading...', 'still loading', 5);
        oWadjaX.send('Update', wProfile.Current.LabelID, '', NewPrivacyID, function (res) {
            if (!res.error) {
                Notify.spinnerOff('done', 1);
            }
            else {
                Notify.spinnerOff('done', 1);
                Notify.alert('', res.error, 'red', 'ok');
            }
        });
    }
    catch (Error) { Notify.alert('No network', 'A network error occurred. Check that you are connected to the internet', 'red', 'ok'); }
}

function LabelPrivacyIcon(privacy) {
  
    if (privacy=='-1')
    {
        if ($('label_privacy'))
        {
            $('label_privacy').addClass('dnd');
            $('label_edit').addClass('dnd');
        }
        
        if ($('link_attach_twitter'))
            $('link_attach_twitter').addClass('dnd');

        return '';//#stop here
    }

    //#disabled: twitter:, message:2, trash:3
    if (wProfile.Current.LabelID !='2' && wProfile.Current.LabelID !='3' && profileInfo.ownerID == profileInfo.viewerID)
    {
        if ($('label_privacy') && wProfile.Current.Category == 'My') {
            $('label_privacy').removeClass('dnd');
            $('label_edit').removeClass('dnd');
           
            $('privacyicon').removeClass('lblPr_2');
            $('privacyicon').removeClass('lblPr_3');
            $('privacyicon').removeClass('lblPr_4');

            $('privacyicon').removeClass('lblPr_2_b');
            $('privacyicon').removeClass('lblPr_3_b');
            $('privacyicon').removeClass('lblPr_4_b');

            $('privacyicon').addClass('lblPr_' + privacy+'');
          
            privacy += ''; //Converts privacy from int to string
            $('privacyicon').set('title', privacy.replace("1", "No one").replace("2", "Only me").replace("3", "Followers").replace("4", "Everyone"));
        }
        //#toggle twitter button
        if (privacy != 4 && wProfile.Current.Category != 'My') {
            if ($('link_attach_twitter'))
                $('link_attach_twitter').addClass('dnd');
        }
        else if (wProfile.Current.Category != 'My') {
            if ($('updateTwitterStatus'))
                $('updateTwitterStatus').addClass('dnd');
        }
        else if (privacy != 4) {
             if ($('updateTwitterStatus'))
                $('updateTwitterStatus').addClass('dnd');
        }
        else {
            if ($('link_attach_twitter'))
                $('link_attach_twitter').removeClass('dnd');
        }
    }
    else
    {
            if ($('link_attach_twitter'))
                $('link_attach_twitter').addClass('dnd');

            if ($('label_privacy'))
            {
                $('label_privacy').addClass('dnd');
                $('label_edit').addClass('dnd');
            }
    }
}

/// #Follow-functions
function InitLabelInfo(oLabelID) {
    ///GET LABEL INFORMATION
    try {
            if (wProfile.Current.LabelID > 0) {
                wjxLabel.send('GetInfo', oLabelID, profileInfo.ownerID, function (res) {
                    if (!res.error) {
                        LabelInfo = JSON.decode(res.value);
                        //#load privacy dropdown
                        LabelPrivacyIcon(LabelInfo.privacy);
                        //#load followers
                        if (profileInfo.ownerWadjaID != 'wadja')
                            ManageFollowLink();
                        //#get followers
                        GetLabelFollowers(oLabelID, LabelInfo.name);
                        
                        //#db request-Get twitter drop-down
                        if (profileInfo.ownerID == profileInfo.viewerID)
                            CheckTwitterForLabel();
                    }
                });
            }
            else {
                if (profileInfo.ownerWadjaID != 'wadja')
                    ManageFollowLink();

                GetLabelFollowers(oLabelID, 'Home');
                //#Hide privacy
                LabelPrivacyIcon('-1');
            }
        
    }
    catch (Error) {
        Notify.alert('Javascript error', '<div class="pad10">Javascript error while loading [InitLabelInfo] #' + Error + '.</div>', 'Ok', 'red');
    }
}

///GET RIGHT SIDE FOLLOWERS
function GetLabelFollowers(LabelID, LabelName) {
    if (LabelID > 0 && wProfile.Current.Category == 'My' && LabelID!=2) {
        var oWadjaX = new WADJAX('labels', { statusBar: false });
  
        try {
            oWadjaX.send('GetFollowersForProfile', LabelID.toString(), profileInfo.ownerID, profileInfo.viewerID, LabelName,profileInfo.ownerWadjaID, function (res) {
                if (!res.error) {
                    if (res.value.trim()=="")
                    {
                          if ($('followers_wrapper'))
                            $('followers_wrapper').addClass('dnd');
                    }
                    else
                    {    
                        
                        LabelOwner = profileInfo.ownerID;
                        if (LabelOwner != "wadja") {
                            if ($('followers_wrapper'))
                                $('followers_wrapper').removeClass('dnd');
                          
                            if ($('followers_container'))
                                $('followers_container').set('html', res.value);
                        }
                        //#add color based on current theme
                        try {
                                $$('.lblDesignColor').each(function (element, index) {
                                        var ttt = element.get('id');
                                        $(ttt).setStyles({
                                            'color': '#' + profileInfo.LinkColor
                                        });
                                    });
                        }
                        catch (Error) {}
                    }
                }
                else
                {
                     if ($('followers_wrapper'))
                        $('followers_wrapper').addClass('dnd');
                }
            });
        }
        catch (Error) {
            Notify.alert('Javascript error', '<div class="pad10">Javascript error while loading [loading followers] #' + Error + '.</div>', 'Ok', 'red');
        }
    }
    else
    {
        if ($('followers_wrapper'))
            $('followers_wrapper').addClass('dnd');
    }
}
function followingToggle(){
  MyElement.toggleReveal('followers_list');
}
function ManageFollowLink() {
    
    //alert(profileInfo.profileBelongsToViewer + " -- " + wProfile.Current.Category);
    //LabelInfo.Owner_ID, wProfile.Current.LabelID, profileInfo.viewerID
    try {
        if (profileInfo.profileBelongsToViewer) {
            if (wProfile.Current.LabelID > 0) {
                if (wProfile.Current.Category == 'Every') {
                    var oWadjaX = new WADJAX('labels', { statusBar: false });
                    if (LabelInfo.Owner_ID > 0)
                        LabelOwner = LabelInfo.Owner_ID.toString();
                    else
                        LabelOwner = profileInfo.ownerID;

                    oWadjaX.send('IsFollower', wProfile.Current.LabelID, LabelOwner, profileInfo.viewerID, function (res) {
                        if (!res.error) {
                            if (res.value == '1') {
                                if ($('aFollow'))
                                {
                                    $('aFollow').removeClass('dnd');
                                    $('aFollow').set('html', '<span onclick=\'StopFollowingLabel();\'>Stop following <b>#' + LabelInfo.name + '</b></span>');
                                    $('aFollow').style.backgroundColor = '#d74848';
                                }
                                FollowLink = 2;
                            }
                            else {
                                if ($('aFollow'))
                                {
                                    $('aFollow').removeClass('dnd');
                                    $('aFollow').set('html', '<span onclick=\'FollowLabel();\'>Follow <b>#' + LabelInfo.name + '</b></span>');
                                    $('aFollow').style.backgroundColor = '#22851E';
                                }
                                FollowLink = 1;
                            }
                        }
                    });

                    $('label_edit').addClass('dnd');
                    $('privacyicon').addClass('dnd');
                }
                else {
                    if (wProfile.Current.Category != 'Follow') {
                        //INVITE TO FOLLOW
                        if (wProfile.Current.LabelID != 2 && wProfile.Current.LabelID != 5 && wProfile.Current.LabelID != 3 && LabelInfo.privacy != 2) {
                            $('aFollow').removeClass('dnd');
                            $('aFollow').set('html', '<span onclick=\'InviteToFollow();\'>Invite to follow <b>#' + LabelInfo.name + '</b></span>');
                            $('aFollow').style.backgroundColor = '#22851E';
                            $('label_edit').removeClass('dnd');
                            $('privacyicon').removeClass('dnd');
                        }
                        else {
                            $('aFollow').addClass('dnd');
                        }
                    }
                    else
                    {
                        if (LabelInfo.Owner_ID > 0)
                            LabelOwner = LabelInfo.Owner_ID.toString();
                        else
                            LabelOwner = profileInfo.ownerID;
                       
                 
                        var oWadjaX = new WADJAX('labels', { statusBar: false });
                        oWadjaX.send('IsFollower', wProfile.Current.LabelID, LabelOwner, profileInfo.viewerID, function (res) {
                            if (!res.error) {
                                if (res.value == '1') {
                                    if ($('aFollow'))
                                    {
                                        $('aFollow').removeClass('dnd');
                                        $('aFollow').set('html', '<span onclick=\'StopFollowingLabel();\'>Stop following <b>#' + LabelInfo.name + '</b></span>');
                                        $('aFollow').style.backgroundColor = '#d74848';
                                    }
                                    FollowLink = 2;
                                }
                                else {
                                    if ($('aFollow'))
                                    {
                                        $('aFollow').removeClass('dnd');
                                        $('aFollow').set('html', '<span onclick=\'FollowLabel();\'>Follow <b>#' + LabelInfo.name + '</b></span>');
                                        $('aFollow').style.backgroundColor = '#22851E';
                                    }
                                    FollowLink = 1;
                                }
                            }
                        });

                        $('label_edit').addClass('dnd');
                        $('privacyicon').addClass('dnd');   
                                        
                    }
                }
            }
            else {
                $('aFollow').addClass('dnd');
            }
        }
        else {

            if (profileInfo.isLoggedIn) {

                if (wProfile.Current.LabelID > 0 && wProfile.Current.LabelID != 2 && LabelInfo.Owner_ID !=profileInfo.viewerID) {

                    if (LabelInfo.Owner_ID > 0)
                        LabelOwner = LabelInfo.Owner_ID.toString();
                    else
                        LabelOwner = profileInfo.ownerID;

                    var oWadjaX = new WADJAX('labels', { statusBar: false });
                    oWadjaX.send('IsFollower', wProfile.Current.LabelID, LabelOwner, profileInfo.viewerID, function (res) {
                        if (!res.error) {

                            if (res.value == '1') {
                                $('aFollow').removeClass('dnd');
                                $('aFollow').set('html', '<span onclick=\'StopFollowingLabel();\'>Stop following <b>#' + LabelInfo.name + '</b></span>');
                                $('aFollow').style.backgroundColor = '#d74848';
                                FollowLink = 2;
                            }
                            else {
                                $('aFollow').removeClass('dnd');
                                $('aFollow').set('html', '<span onclick=\'FollowLabel();\'>Follow <b>#' + LabelInfo.name + '</b></span>');
                                $('aFollow').style.backgroundColor = '#22851E';
                                FollowLink = 1;
                            }
                        }
                    });
                }
                else {
                    if (wProfile.Current.Category == 'My' && wProfile.Current.LabelID == 0 && profileInfo.profileBelongsToViewer) {
                        var oWadjaX = new WADJAX('labels', { statusBar: false });
                        oWadjaX.send('IsFollower', '8', profileInfo.ownerID, profileInfo.viewerID, function (res) {
                            if (!res.error) {
                                if (res.value == '1') {
                                    $('aFollow').removeClass('dnd');
                                    $('aFollow').set('html', '<span onclick=\'StopFollowingLabel();\'>Stop following <b>#Home</b></span>');
                                    $('aFollow').style.backgroundColor = '#d74848';
                                    FollowLink = 2;
                                }
                                else {
                                    $('aFollow').removeClass('dnd');
                                    $('aFollow').set('html', '<span onclick=\'FollowLabel();\'>Follow <b>#Home</b></span>');
                                    $('aFollow').style.backgroundColor = '#22851E';
                                    FollowLink = 1;
                                }
                            }
                        });
                    }
                    else
                        $('aFollow').addClass('dnd');
                }
            }
            else {
                //ANONYMOUS USER
                if (wProfile.Current.LabelID > 0 && wProfile.Current.LabelID != 2) {
                    $('aFollow').removeClass('dnd');
                    $('aFollow').set('html', '<span onclick=\'location.href="/sessions/landingpage.aspx?labelid=' + wProfile.Current.LabelID.toString() + '&ownerID=' + profileInfo.ownerID + '"\'>Follow <b>#' + LabelInfo.name.replace("'", "//'") + '</b></span>');
                    $('aFollow').style.backgroundColor = '#22851E';
                    FollowLink = 1;
                }
                else {
                    if (wProfile.Current.Category == 'My') {
                        $('aFollow').removeClass('dnd');
                        $('aFollow').set('html', '<span onclick=\'location.href="/sessions/landingpage.aspx?labelid=8&ownerID=' + profileInfo.ownerID + '"\'>Follow <b>#Home</b></span>');
                        $('aFollow').style.backgroundColor = '#22851E';
                        FollowLink = 1;
                    }
                    else
                        $('aFollow').addClass('dnd');
                }
            }

            $('label_edit').addClass('dnd');
            $('privacyicon').addClass('dnd');
        }
    }
    catch (Error) { }

    try {
        if (justFollowed)
            $('aFollow').addClass('dnd');
    }
    catch (Error) { }
}

function FollowLabel() {
    try {
        LabelName = LabelInfo.name.replace("'", "//'");
        LabelID = wProfile.Current.LabelID.toString();
        if (LabelInfo.Owner_ID > 0)
            LabelOwner = LabelInfo.Owner_ID.toString();
        else
            LabelOwner = profileInfo.ownerID;
    }
    catch (Error) {
        LabelName = 'Home'
        LabelOwner = profileInfo.ownerID;
        LabelID = '8';
    }

    var oWadjaX = new WADJAX('labels', { statusBar: false });
    oWadjaX.send('Follow', LabelID, LabelOwner, profileInfo.viewerID.toString(), '', function (res) {
        if (!res.error) {
            $('aFollow').removeClass('dnd');
            $('aFollow').set('html', '<span onclick=\'StopFollowingLabel();\'>Stop following <b>#' + LabelName + '</b></span>');
            $('aFollow').style.backgroundColor = '#d74848';
            FollowLink = 2;
            Notify.topBarOn('You are now following label #' + LabelName, '', 6);
        }
    });
}
function StopFollowingLabel() {
    try {
        LabelName = LabelInfo.name.replace("'", "//'");
        LabelID = wProfile.Current.LabelID.toString();
        if (LabelInfo.Owner_ID > 0)
            LabelOwner = LabelInfo.Owner_ID.toString();
        else
            LabelOwner = profileInfo.ownerID;
    }
    catch (Error) {
        LabelName = 'Home'
        LabelOwner = profileInfo.ownerID;
        LabelID = '8';
    }

    var oWadjaX = new WADJAX('labels', { statusBar: false });
    oWadjaX.send('StopFollowingLabel', LabelID, LabelOwner, profileInfo.viewerID.toString(), '', '', function (res) {
        if (!res.error) {
            $('aFollow').removeClass('dnd');
            $('aFollow').set('html', '<span onclick=\'FollowLabel();\'>Follow <b>#' + LabelName + '</b></span>');
            $('aFollow').style.backgroundColor = '#22851E';
            FollowLink = 2;
            Notify.topBarOn('You have stopped following label #' + LabelName, '', 6);
        }
    });
}

function FollowSpecificLabel(pLblId, pLblName, pOwnerId, pOwnerStringID) {
   
    var oWadjaX = new WADJAX('labels', { statusBar: false });
    oWadjaX.send('Follow', pLblId, pOwnerId, profileInfo.viewerID.toString(), '', function (res) {
        if (!res.error) {
            //#transition starts here...
             $('dvRandomFeed_' + pLblId.toString()).setStyle('display', 'block').fade('out'); 
            (function () { 
              $('dvRandomFeed_' + pLblId.toString()).setStyle('display', 'block').fade('in'); 
              $('dvRandomFeed_' + pLblId.toString()).set('class','tac randomfeed_follow clearboth');
              $('dvRandomFeed_' + pLblId.toString()).set('html','<div class=\"grayColor textShadow pad5 f11 dnb\">You are now following label <a href=\"/'+ pOwnerStringID+'#!My/'+pLblId+'/1\">#' + pLblName + '</a></div>');
            }).delay(1 * 1000);
            //#transition ends here.
            var suggestedLabelList = $('dvRndLabelsContainer').getChildren('div');
            var allSuggestedAreHidden = true;
            for (var i = 0; i < suggestedLabelList.length; i++) {
                if (!suggestedLabelList[i].hasClass('dnd')) {
                    allSuggestedAreHidden = false;
                    break;
                }
            }
            if (allSuggestedAreHidden) {
                //put code here!
                //alert('all suggestions are hidden!');
                $('connect_labels_nofeed').addClass('dnd');
            }
        }
    });
}

function ClosenoFeed() {
    if ($('neverShow').checked)
        CloseNews('1');
    else {
        $('noFeeds').addClass('dnd');
        //$('master_feeds_container').removeClass('dnd');
    }

}

function CloseNews(action) {
    //action:0:turn off  per label, 1: turn off for all labels
    if (action == 0)
        elementID = selectedLabelName;
    else if (action == 1)
        elementID = 'off';

    Notify.spinnerOn('loading...', 'still loading', 5);
    var oWadjaX = new WADJAX('Misc', { statusBar: false });

    oWadjaX.send('CloseProfileNews', elementID, function (res) {
        if (!res.error)
            Notify.spinnerOff('done', 1);
        else
            Notify.spinnerOff('done', 1);
    });
    MyElement.dissolve('noFeeds');
}

var GetExternalFeeds = function () {
    if(profileInfo.profileBelongsToViewer) {
        //wjxShhProfile.send('GetExternalFeeds', profileInfo.ownerID, 1, wProfile.Current.LabelID, function (res) { }); //Digg
        wjxShhProfile.send('GetExternalFeeds', profileInfo.ownerID, 2, wProfile.Current.LabelID, function (res) { }); //Twitter
        wjxShhProfile.send('GetExternalFeeds', profileInfo.ownerID, 3, wProfile.Current.LabelID, function (res) { }); //LastFM
        wjxShhProfile.send('GetExternalFeeds', profileInfo.ownerID, 4, wProfile.Current.LabelID, function (res) { }); //Youtube
    }
}

function setTxtBodyText() {
    if ($('txtBody')) {
        $('txtBody').addClass('type_message');
        $('txtBody').value = 'Click here to type your message...';
    }

    if($('dvCounter') && $('txtBody')) {
        maxchar = 500;
        $('dvCounter').addClass('dnd');
        $('dvCounter').innerHTML = maxchar - $('txtBody').value.length;
    }

    if($('smsFromDDL'))
        $('smsFromDDL').innerHTML = '';
    
    if($('txtTo')) {
        var selectedLabelID = parseInt(wProfile.Current.LabelID);
        var postVar = GetUserAndLabel(selectedLabelID);
        if (!profileInfo.profileBelongsToViewer && postVar == '')
            postVar = '@' + profileInfo.ownerWadjaID + ' ';
        else if (profileInfo.profileBelongsToViewer && postVar == '')
            postVar = '@';
        var smsVar = '+';
        if (!profileInfo.profileBelongsToViewer && profileInfo.ownerVerified === 'true')
            smsVar = '+' + profileInfo.ownerWadjaID + ' ';

        if(selectedLabelID==0) {
            $('txtTo').addClass('type_message');
            $('txtTo').value = 'Type @ or + here...';
            ComposeOverlay.Hide();
            $('dvFound').getElement('span').innerHTML = "<a class=\"blueSms\" href=\"javascript:SetTextBox('" + postVar + "');\">Post (@)</a> or <a class=\"greenSms\" href=\"javascript:SetTextBox('" + smsVar + "');\">SMS (+)</a>";
        }
        else{
            $('txtTo').removeClass('type_message')
            $('txtTo').value = GetUserAndLabel(selectedLabelID);
            if ($('txtTo').value != '')
                wjxShhProfile.send('WdjThnk', $('txtBody').value, $('txtTo').value, wProfile.Compose.WadjaThinking);
        }
    }
    
//    if(!$('txtTo').hasClass('dndD')) {
//        
//        if ($('txtTo')) {
//            $('txtTo').value = GetUserAndLabel(selectedLabelID);
//            if ($('txtTo').value != '')
//                wjxShhProfile.send('WdjThnk', $('txtBody').value, $('txtTo').value, wProfile.Compose.WadjaThinking);
//            else {
//                
//                
//            }
//        }
//    }
//    else {
//        var selectedLabelID = parseInt(wProfile.Current.LabelID);
//        var postVar = GetUserAndLabel(selectedLabelID);
//        if (!profileInfo.profileBelongsToViewer && postVar == '')
//            postVar = '@' + profileInfo.ownerWadjaID + ' ';
//        else if (profileInfo.profileBelongsToViewer && postVar == '')
//            postVar = '@';
//        var smsVar = '+';
//        if (!profileInfo.profileBelongsToViewer && profileInfo.ownerVerified === 'true')
//            smsVar = '+' + profileInfo.ownerWadjaID + ' ';
//        $('dvFound').getElement('span').innerHTML = "<a class=\"blueSms\" href=\"javascript:SetTextBox('" + postVar + "');\">Post (@)</a> or <a class=\"greenSms\" href=\"javascript:SetTextBox('" + smsVar + "');\">SMS (+)</a>";    
//    }
}

function GetUserAndLabel(labelID) {
    var res = '';
    var labelname = '';
    var labelowner = '';

    if(labelID == 2) return '';
    
    if (wProfile.Current.Category == 'My')
        res = JSON.decode(jsHelper.cachedData.My);
    
    if (wProfile.Current.Category == 'Follow')
        res = JSON.decode(jsHelper.cachedData.Follow);

    if (res == null) return '';

    for (var i = 0; i < res.length; i++) {
        if (res[i].labelID == labelID) {
            labelname = res[i].labelName;
            labelowner = res[i].OwnerWadjaID;
            break;
        }
    }

    if (profileInfo.ownerID == wProfile.Current.ViewerID && labelname == '' && wProfile.Current.Category == 'My')
        return '';
    else if (profileInfo.ownerID == wProfile.Current.ViewerID && wProfile.Current.Category == 'My')
      return '@' + profileInfo.ownerWadjaID + ' #' + labelname + ' ';
//    else if (profileInfo.ownerID == wProfile.Current.ViewerID && labelname == '' && wProfile.Current.Category == 'My')
//        return '@' + profileInfo.ownerWadjaID + ' ';
//    else if (profileInfo.ownerID != wProfile.Current.ViewerID && labelname == '' && wProfile.Current.Category == 'My')
//        return '@' + profileInfo.ownerWadjaID + ' ';
    else if (profileInfo.ownerID != wProfile.Current.ViewerID && labelname != '' && wProfile.Current.Category == 'My')
        return '@' + profileInfo.ownerWadjaID + ' #' + labelname + ' ';
    else if (wProfile.Current.Category == 'Follow' && labelowner != '')
        return '@' + labelowner + ' #' + labelname + ' ';
    else
        return '';
    
}

function SetTextBox(text) {
    if ($('txtTo')) {
        $('txtTo').removeClass('type_message');
        $('txtTo').value = text;
        if (!($('txtTo').value == '' || $('txtTo').value == '@' || $('txtTo').value == '+'))
            wjxShhProfile.send('WdjThnk', $('txtBody').value, $('txtTo').value , wProfile.Compose.WadjaThinking);
        else {
            if($('txtTo').value == '@') {
                $('sendNote').innerHTML = 'Post to: ';
            }
            else if($('txtTo').value == '+') {
                $('sendNote').innerHTML = 'SMS to: ';
            }
            else {
                $('sendNote').innerHTML = '<a class=\"blueSms\" href=\"javascript:SetTextBox(\'@\');\">Post (@)</a> or <a  class=\"greenSms\" href=\"javascript:SetTextBox(\'+\');\">SMS (+)</a>';
            }
            $('smsFromDDL').innerHTML = '';
        }
        $('txtTo').focus();
        $('txtTo').setCaretPosition('end');
    }
}

var helpTooltips = {
    On: function () {
        var randomnumber = Math.floor(Math.random() * 2)
        var tip = "Example: #home Hello world check out my home label.";
        //+
        //#
        //@
        if (randomnumber == 0)
            tip = 'Example: #home Hello world check out my HOME profile label.';
        else if (randomnumber == 1)
            tip = 'Example: @mary #iphone I like your blog post about the new iPhone.';
        else if (randomnumber == 2)
            tip = 'Example: +tom Call me when you receive this SMS';

        Tip.doTipOn_('profile_compose_send', 'Example: #home Hello world check out my home label.', '10');
    },
    Off: function () {
        Tip.doTipOff('profile_compose_send');
    }
}


var ITFFB = null;
function InviteToFollow() {
    LabelID = wProfile.Current.LabelID.toString();
    ITFFB = new Facebox({
        url: '/contacts/invite/iframe.aspx?oid=' + profileInfo.ownerID + '&vid=' + profileInfo.viewerID + '&labelid=' + LabelID,
        width: 520,
        height: 380,
        title: 'Invite to follow',
        submitValue: 'Send Invites',
        submitFunction: function () {
            var inviteSent = document.getElementById('frame_file').contentWindow.SendInvitations();
        },
        cancelValue: 'Cancel',
        cancelFunction: function () {
            ITFFB.close();
        }
    });
    ITFFB.show();
}
function InviteToFollow_share(shlabelid,shlabelOwnerID) {
    LabelID = wProfile.Current.LabelID.toString();
    ITFFB = new Facebox({
        url: '/contacts/invite/iframe.aspx?oid=' + shlabelOwnerID + '&vid=' + profileInfo.viewerID + '&labelid=' + shlabelid + '&share=1',
        width: 520,
        height: 380,
        title: 'Invite to follow',
        submitValue: 'Send Invites',
        submitFunction: function () {
        //alert(profileInfo.ownerID + "---" + shlabelOwnerID);
            if(profileInfo.ownerID == shlabelOwnerID && profileInfo.viewerID == shlabelOwnerID)
                var inviteSent = document.getElementById('frame_file').contentWindow.SendInvitations();
            else
                var inviteSent = document.getElementById('frame_file').contentWindow.SendInvitationsForOther();
        },
        cancelValue: 'Cancel',
        cancelFunction: function () {
            ITFFB.close();
        }
    });
    ITFFB.show();
}
///SEARCH FILTERS
var searchFilter = {
    by: function (filterID) {
        //handle on/off
        $(filterID).addClass('filter_on');
        $(filterID).removeClass('filter_off');
        //sfilter:no existent class, used by the js only
        $$('.sfilter').each(function (element, index) {
            var filters = element.get('id');

            if (filterID.toLowerCase() != filters.toLowerCase()) {
                $(filters).addClass('filter_off');
                $(filters).removeClass('filter_on');
            }
        });
        //load filter results here
        // - type your code here -
        wProfile.CurrentSearch.Page = 1;
        if (filterID.toLowerCase() == 'filter_search_all') {
            wProfile.CurrentSearch.Category = 'feeds';
            //wProfile.Search(wProfile.CurrentSearch.Category, wProfile.CurrentSearch.Keyword);
            top.location.hash = '!search?searchType=' + '&searchFor=' + wProfile.CurrentSearch.Keyword;
        }
        else if (filterID.toLowerCase() == 'filter_search_people') {
            wProfile.CurrentSearch.Category = 'contacts';
            //wProfile.Search(wProfile.CurrentSearch.Category, wProfile.CurrentSearch.Keyword);
            top.location.hash = '!search?searchType=contacts' + '&searchFor=' + wProfile.CurrentSearch.Keyword;
        }
        else if (filterID.toLowerCase() == 'filter_search_labels') {
            wProfile.CurrentSearch.Category = 'labels';
            //wProfile.Search(wProfile.CurrentSearch.Category, wProfile.CurrentSearch.Keyword);
            top.location.hash = '!search?searchType=labels' + '&searchFor=' + wProfile.CurrentSearch.Keyword;
        }
        else if (filterID.toLowerCase() == 'filter_search_web') {
            wProfile.CurrentSearch.Category = 'web';
            wProfile.Search(wProfile.CurrentSearch.Category, wProfile.CurrentSearch.Keyword);
        }
    }
}

///HASH.JS
/*!
* Copyright (c) 2009 Andreas Blixt <andreas@blixt.org>
* Contributors: Aaron Ogle <aogle@avencia.com>,
*               Matti Virkkunen <mvirkkunen@gmail.com>
* This and more JavaScript libraries: http://blixt.org/js
* MIT License: http://www.opensource.org/licenses/mit-license.php
* 
* History handler
* Keeps track of the history of changes to the hash part in the address bar.
*/
/* WARNING for Internet Explorer 7 and below:
* If an element on the page has the same ID as the hash used, the history will
* get messed up.
*
* Does not support history in Safari 2 and below.
* 
* Example:
*     function handler(newHash, initial) {
*         if (initial)
*             alert('History is "' + newHash + '"');
*         else
*             alert('History changed to "' + newHash + '"');
*     }
*     History.init(handler, document.getElementById('hidden-iframe'));
*     History.go('abc123');
* 
* Updated by Matti Virkkunen (mvirkkunen@gmail.com) on 2009-11-16:
*   - Added second argument to callback that indicated whether the callback is due
*     to initial state (true) or due to an actual change to the hash (false).
* 
* Updated by Aaron Ogle (aogle@avencia.com) on 2009-08-11:
*   - Fixed bug where Firefox automatically unescapes location.hash but no other
*     browsers do. Always get the hash by parsing location.href and never use
*     location.hash.
*/

var History = (function () {
    var 
    // Import globals
window = this,
documentMode = document.documentMode,
history = window.history,
location = window.location,
    // Plugin variables
callback, hash,
    // IE-specific
iframe,

getHash = function () {
    // Internet Explorer 6 (and possibly other browsers) extracts the query
    // string out of the location.hash property into the location.search
    // property, so we can't rely on it. The location.search property can't be
    // relied on either, since if the URL contains a real query string, that's
    // what it will be set to. The only way to get the whole hash is to parse
    // it from the location.href property.
    //
    // Another thing to note is that in Internet Explorer 6 and 7 (and possibly
    // other browsers), subsequent hashes are removed from the location.href
    // (and location.hash) property if the location.search property is set.
    //
    // Via Aaron: Firefox 3.5 (and below?) always unescape location.hash which
    // causes poll to fire the hashchange event twice on escaped hashes. This is
    // because the hash variable (escaped) will not match location.hash
    // (unescaped.) The only consistent option is to rely completely on
    // location.href.
    var index = location.href.indexOf('#');
    return (index == -1 ? '' : location.href.substr(index + 1));
},

    // Used by all browsers except Internet Explorer 7 and below.
poll = function () {
    var curHash = getHash();
    if (curHash != hash) {
        hash = curHash;
        callback(curHash, false);
    }
},

    // Used to create a history entry with a value in the iframe.
setIframe = function (newHash) {
    try {
        var doc = iframe.contentWindow.document;
        doc.open();
        doc.write('<html><body>' + newHash + '</body></html>');
        doc.close();
        hash = newHash;
    } catch (e) {
        setTimeout(function () { setIframe(newHash); }, 10);
    }
},

    // Used by Internet Explorer 7 and below to set up an iframe that keeps track
    // of history changes.
setUpIframe = function () {
    // Don't run until access to the iframe is allowed.
    try {
        iframe.contentWindow.document;
    } catch (e) {
        setTimeout(setUpIframe, 10);
        return;
    }

    // Create a history entry for the initial state.
    setIframe(hash);
    var data = hash;

    setInterval(function () {
        var curData, curHash;

        try {
            curData = iframe.contentWindow.document.body.innerText;
            if (curData != data) {
                data = curData;
                location.hash = hash = curData;
                callback(curData, true);
            } else {
                curHash = getHash();
                if (curHash != hash) setIframe(curHash);
            }
        } catch (e) {
        }
    }, 50);
};

    return {
        init: function (cb, ifr) {
            // init can only be called once.
            if (callback) return;

            callback = cb;

            // Keep track of the hash value.
            hash = getHash();
            cb(hash, true);

            // Run specific code for Internet Explorer.
            if (window.ActiveXObject) {
                if (!documentMode || documentMode < 8) {
                    // Internet Explorer 5.5/6/7 need an iframe for history
                    // support.
                    iframe = ifr;
                    setUpIframe();
                } else {
                    // Internet Explorer 8 has onhashchange event.
                    window.attachEvent('onhashchange', poll);
                }
            } else {
                // Change Opera navigation mode to improve history support.
                if (history.navigationMode) history.navigationMode = 'compatible';

                setInterval(poll, 50);
            }
        },

        go: function (newHash) {
            // Cancel if the new hash is the same as the current one, since there
            // is no cross-browser way to keep track of navigation to the exact
            // same hash multiple times in a row. A wrapper can handle this by
            // adding an incrementing counter to the end of the hash.
            if (newHash == hash) return;
            if (iframe) {
                setIframe(newHash);
            } else {
                location.hash = hash = newHash;
                callback(newHash, false);
            }
        }
    };
})();

function handler(newHash, initial) {
    clearInterval(refTimer);
    if ($('aNewFeeds'))
    {
        new Fx.Reveal($('aNewFeeds'), { duration: 500 }).dissolve();
        new Fx.Reveal($('newfeeds_wrapper'), { duration: 500 }).dissolve();
    
    }
    if (initial && newHash == "") {
        if (isDomReady)
        {
            wProfile.Load(wProfile.Current.DetailsID, "My", 0, 1, true);
        }
    }
    else if (newHash.indexOf('!inbox') == 0) {
        var oQ = newHash.substring(1).split('/');
        wProfile.Inbox(oQ[1]);
    } else if (newHash.indexOf('!search') == 0) {
        var oQ = newHash.substring(1).split('?');
        var qsValues = oQ[1].parseQueryString();
        //set search filters
        var filterID = '';
        switch (qsValues.searchType.toLowerCase()){
            case '':
            case 'feeds':
            filterID = 'filter_search_all';
            break;
            case 'contacts':
            filterID = 'filter_search_people';
            break;
            case 'labels':
            filterID = 'filter_search_labels';
            break;
        }
        $(filterID).addClass('filter_on');
        $(filterID).removeClass('filter_off');
        //sfilter:no existent class, used by the js only
        $$('.sfilter').each(function (element, index) {
            var filters = element.get('id');
            if (filterID.toLowerCase() != filters.toLowerCase()) {
                $(filters).addClass('filter_off');
                $(filters).removeClass('filter_on');
            }
        });
        wProfile.Search(qsValues.searchType, qsValues.searchFor);
    } else if (newHash.indexOf('!') == 0) {
        var oQ = newHash.substring(1).split('/');
        if (isDomReady)
        {
            wProfile.Load(wProfile.Current.DetailsID, oQ[0], oQ[1], oQ[2], true);
        }
        else
        {   //#When refreshing page on a selected label and domready is not ready wait for 5 sec and load feeds
            (function () { wProfile.Load(wProfile.Current.DetailsID, oQ[0], oQ[1], oQ[2], true); }).delay(2 * 1000);
        }
    }
}

History.init(handler, $('ajax-hidden-iframe'));

function AttachPhoto(mID) {
    Notify.spinnerOff('Done!', 1);
    if ($('photo_attached')) {
        $('photo_attached').removeClass('dnd');
        $('link_attach_photo').removeClass('uploadMedia');
        $('link_attach_photo').addClass('uploadMediaAtt');
    }
    mediaID = mID;
}

function DeletePhoto() {
    if ($('photo_attached')) {
                $('photo_attached').addClass('dnd');
                $('link_attach_photo').removeClass('uploadMediaAtt');
                $('link_attach_photo').addClass('uploadMedia');
            }

    oWUser.send('DeletePhoto', mediaID, function (res) {
        if (res.error) return;
        if (res.value == '1') {
            
            mediaID = 0;
        }
    });
}

function CheckTwitterForLabel() {
    if (profileInfo.viewerID == profileInfo.ownerID) {
        wjxShhProfile.send('CheckTwitterForLabel', profileInfo.ownerID, wProfile.Current.LabelID + ',', function (res) {
            if (res.error) return;
            Twitter.empty();
            $$('.twitterCheckBox').each(function (element, index) {
                    $(element.get('id')).checked = false;
            });
            var cID = JSON.decode(res.value);
            for(var i = 0; i < cID.length; i++) {

                var element = 'chkTwCon_' + cID[i];
                if ($(element)) {
                    $(element).checked = 'true';
                    Twitter.push(cID[i]);
                }
            }
            // show the appropriate Twitter icon
            if (Twitter.length > 0) {
                $('link_attach_twitter').removeClass('autoTwitter');
                $('link_attach_twitter').addClass('autoActiveTwitter');
            }
            else {
                $('link_attach_twitter').removeClass('autoActiveTwitter');
                $('link_attach_twitter').addClass('autoTwitter');
            }
        });
    }
}

///#GetMeta info
var MetaTags= {
    get: function(URL,URLType){
         
         //#URLType: When you click attach link
         if (URL.indexOf('http://') >= 0 && !MetaInfo)//&& (profileInfo.ownerWadjaID=='argyris' || profileInfo.ownerWadjaID=='alex' || profileInfo.ownerWadjaID=='vfarad') 
         {
       
               //#Hide attach: youtube, link icons
               $('preview_metainfo').removeClass('dnd');
               $('load_metainfo').removeClass('dnd');
               
               oWUser.send('GetMeta',URL, function (res) {
                       if (!res.error){
                           try {
                                    //MyElement.dissolve('load_metainfo');
                                    //MyElement.reveal('metainfo_container');
                                    $('load_metainfo').addClass('dnd');
                                    $('metainfo_container').removeClass('dnd');

                                    //debug:Notify.alert('WDzilla!',res.value.trim(),'ok', 'red');
                                    var metaJSON= JSON.decode(res.value.trim());
                                    //#reset
                                    MetaInfoValue = '';

                                    if (metaJSON.youtubeEmbed!=null && metaJSON.youtubeEmbed!="")
                                    {
                                      //#video url
                                      $('metainfo_link').set('html',metaJSON.link);
                                      $('metainfo_link').set('href',metaJSON.link);
                                      //#site_name
                                      $('sitename').set('html','Youtube video');
                                      //#title
                                      $('metainfo_title').set('html','<a href=\"'+metaJSON.youtubeEmbed.author_url+'">' + metaJSON.youtubeEmbed.author_name + '</a>  - ' +  metaJSON.youtubeEmbed.title);
                                      //#description
                                      $('metainfo_descrpition').set('html',metaJSON.description);
                                      //#video thumb
                                      $('metainfo_image').set('src',  metaJSON.youtubeEmbed.thumbnail_url);
                                      $('metainfo_image_div').removeClass('dnd');

                                      //#share feeds
                                      MetaInfoValue +='{';
                                      MetaInfoValue +='thumb:"'+metaJSON.youtubeEmbed.thumbnail_url+'",';
                                      MetaInfoValue +='description:"'+ metaJSON.description+'",';
                                      MetaInfoValue +='title:"'+metaJSON.youtubeEmbed.title+'",';
                                      MetaInfoValue +='embed:"'+metaJSON.youtubeEmbed.html.replace(/\"/g,'\'')+'",';
                                      
                                      MetaInfoValue +='url:"'+metaJSON.link+'",';
                                      MetaInfoValue +='author_name:"'+metaJSON.youtubeEmbed.author_name+'",';
                                      MetaInfoValue +='author_url:"'+metaJSON.youtubeEmbed.author_url+'"';
                                      MetaInfoValue +='}';
                                    }
                                    else
                                    {
                                        //#share feeds
                                        MetaInfoValue +='{';

                                        if (metaJSON.image!=null) {
                                            //metainfo_choose_thumb
                                            var image_array= '';
                                            image_array = metaJSON.image.split(",");
                                            MetaThumb='';
                                            if (image_array.length>0 && image_array[0]!='')
                                            { 
                                                //#declare some variable
                                                MetaThumb = image_array[0];
                                                MetaThumblist=1;
                                                //#set first thumb
                                                $('metainfo_image').set('src', image_array[0]);
                                                $('metainfo_image_div').removeClass('dnd');
                                                //#show hide-choose thumb
                                                if (image_array.length>1)
                                                {
                                                    $('metainfo_choose_thumb').removeClass('dnd');
                                                    $('metainfo_choose_thumb_text').set('html', '1 of '+image_array.length);
                                                    
                                                    $('metainfo_choose_thumb_next').addEvent('click', function (event) {

                                                       if (MetaThumblist < image_array.length)
                                                       {   
                                                           ++MetaThumblist;

                                                           $('metainfo_choose_thumb_text').set('html', MetaThumblist + ' of '+image_array.length+ ' ');
                                                           $('metainfo_image').set('src', image_array[MetaThumblist-1]);
                                                       
                                                           var dummy = JSON.decode(MetaInfoValue);
                                                         
                                                           MetaInfoValue  ='';//#reset json
                                                           MetaInfoValue +='{';
                                                           MetaInfoValue +='thumb:"'+image_array[MetaThumblist-1]+'",';
                                                           MetaInfoValue +='description:"'+ dummy.description+'",';
                                                           MetaInfoValue +='title:"'+dummy.title+'",';
                                                           MetaInfoValue +='embed:"",';
                                      
                                                           MetaInfoValue +='url:"'+dummy.url+'",';
                                                           MetaInfoValue +='author_name:"'+dummy.author_name+'",';
                                                           MetaInfoValue +='author_url:"'+dummy.author_url+'"';
                                                           MetaInfoValue +='}';

                                                           
                                                       }
                                                       else if (MetaThumblist == image_array.length)
                                                       {
                                                           $('metainfo_choose_thumb_text').set('html', MetaThumblist + ' of '+image_array.length+ ' ');
                                                           $('metainfo_image').set('src', image_array[MetaThumblist-1]);
                                                       
                                                           var dummy = JSON.decode(MetaInfoValue);
                                                       
                                                           MetaInfoValue  ='';//#reset json
                                                           MetaInfoValue +='{';
                                                           MetaInfoValue +='thumb:"'+image_array[MetaThumblist-1]+'",';
                                                           MetaInfoValue +='description:"'+ dummy.description+'",';
                                                           MetaInfoValue +='title:"'+dummy.title+'",';
                                                           MetaInfoValue +='embed:"",';
                                      
                                                           MetaInfoValue +='url:"'+dummy.url+'",';
                                                           MetaInfoValue +='author_name:"'+dummy.author_name+'",';
                                                           MetaInfoValue +='author_url:"'+dummy.author_url+'"';
                                                           MetaInfoValue +='}';

                                                            //#disable next
                                                       }
                                                       
                                                    }); 
                                                    $('metainfo_choose_thumb_prev').addEvent('click', function (event) {
                                                      
                                                     
                                                       if (MetaThumblist > 1)
                                                       {
                                                           MetaThumblist = MetaThumblist - 1;
                                                           $('metainfo_choose_thumb_text').set('html', MetaThumblist + ' of '+image_array.length + ' ');
                                                           $('metainfo_image').set('src', image_array[MetaThumblist-1]);
                                                       
                                                           var dummy = JSON.decode(MetaInfoValue);
                                                      
                                                           MetaInfoValue  ='';//#reset json
                                                           MetaInfoValue +='{';
                                                           MetaInfoValue +='thumb:"'+image_array[MetaThumblist-1]+'",';
                                                           MetaInfoValue +='description:"'+ dummy.description+'",';
                                                           MetaInfoValue +='title:"'+dummy.title+'",';
                                                           MetaInfoValue +='embed:"",';
                                      
                                                           MetaInfoValue +='url:"'+dummy.url+'",';
                                                           MetaInfoValue +='author_name:"'+dummy.author_name+'",';
                                                           MetaInfoValue +='author_url:"'+dummy.author_url+'"';
                                                           MetaInfoValue +='}';
                                                      
                                                           
                                                       }
                                                       else if  (MetaThumblist == 1)
                                                       {
                                                           $('metainfo_choose_thumb_text').set('html', MetaThumblist + ' of '+image_array.length + ' ');
                                                           $('metainfo_image').set('src', image_array[MetaThumblist-1]);
                                                       
                                                           var dummy = JSON.decode(MetaInfoValue);
                                                      
                                                           MetaInfoValue  ='';//#reset json
                                                           MetaInfoValue +='{';
                                                           MetaInfoValue +='thumb:"'+image_array[MetaThumblist-1]+'",';
                                                           MetaInfoValue +='description:"'+ dummy.description+'",';
                                                           MetaInfoValue +='title:"'+dummy.title+'",';
                                                           MetaInfoValue +='embed:"'+dummy.description.replace(/\"/g,'\'')+'",';
                                      
                                                           MetaInfoValue +='url:"'+dummy.url+'",';
                                                           MetaInfoValue +='author_name:"'+dummy.author_name+'",';
                                                           MetaInfoValue +='author_url:"'+dummy.author_url+'"';
                                                           MetaInfoValue +='}';
                                                           
                                                           //#disable previous
                                                       }
                                                    });
                                                }
                                            }
                                            else
                                            {
                                                $('metainfo_image_div').addClass('dnd');
                                                //?$('metainfo_choose_thumb').addClass('dnd');
                                            }
                                            MetaInfoValue +='thumb:"'+MetaThumb+'",';
                                        }
                                        else
                                        {
                                            $('metainfo_image_div').addClass('dnd');
                                            MetaInfoValue +='thumb:"",';
                                        }

                                        if (metaJSON.description!=null)
                                        {
                                            $('metainfo_descrpition').set('html', metaJSON.description);
                                            MetaInfoValue +='description:"'+ metaJSON.description+'",';
                                        }
                                        else
                                            MetaInfoValue +='description:"",';

                                        if (metaJSON.title!=null){
                                           var title = metaJSON.title;
                                           if (title.trim()=='')
                                                title="External link";

                                           $('metainfo_title').set('html', title);
                                           MetaInfoValue +='title:"'+title+'",';
                                        }
                                        else
                                        {
                                          $('metainfo_title').set('html', 'External link');
                                          MetaInfoValue +='title:"External link",';
                                        }

                                        MetaInfoValue +='embed:"",';

                                        if (metaJSON.link!=null) {
                                            $('metainfo_link').set('html',metaJSON.link);
                                            $('metainfo_link').set('href',metaJSON.link);
                                            MetaInfoValue +='url:"'+metaJSON.link+'",';
                                        }
                                        else
                                        {
                                            MetaInfoValue +='url:"",';
                                        }
                                        
                                        if (metaJSON.site_name!=null && metaJSON.site_name!='')
                                        {   
                                            $('sitename').set('html', metaJSON.site_name);
                                            MetaInfoValue +='author_name:"'+ metaJSON.site_name+'",';
                                        }
                                        else
                                        {
                                            $('sitename').set('html','External link');
                                            MetaInfoValue +='author_name:"'+metaJSON.youtubeEmbed.author_name+'",';
                                        }
                                        if (metaJSON.link!=null)
                                            MetaInfoValue +='author_url:"'+metaJSON.link+'"';
                                        else
                                            MetaInfoValue +='author_url:""';
                                        MetaInfoValue +='}';
                                    }
                                    MetaInfo = true;
                                    //Hide form
                                    if ($('attach_canvas_main'))
                                        $('attach_canvas_main').addClass('dnd');
                               }
                               catch(Error)
                               {
                                    //#debug:Notify.alert('Javascript error', '<div class=\"pad5\">Javascript error while using [GetMeta:'+Error+'] #' + res.value + '</div>', 'Ok', 'red');
                                    MetaTags.remove();
                                    attachCanvas.toggle('close');
                                    //#Notify.alert('Link', '<div class=\"f11 pad5\">This content is not currently available.</div>', 'Ok', '');return;
                               }
                       }
                       else
                       {     
                             MetaInfo = false;
                             MyElement.dissolve('load_metainfo');
                             MyElement.dissolve('metainfo_container');
                             
                             //debug:
                             Notify.alert('Javascript error', 'Javascript error while using [aj.GetMeta] #' + res.error, 'Ok', 'red');
                       }
               });
        }
        else
        {
            Notify.alert('Invalid URL', '<div class=\"pad5\">URL must start with http://</div>', 'Ok', 'red');
            return;
        }
    },
    remove: function(){
        $('preview_metainfo').addClass('dnd');
        $('metainfo_container').addClass('dnd');
        $('load_metainfo').addClass('dnd');

        //#Display attach: link, youtube
        $('link_attach_link').removeClass('dnd');
        $('link_attach_song').removeClass('dnd');
        $('link_attach_youtube').removeClass('dnd');
        $('link_attach_photo').removeClass('dnd');
        $('link_attach_twitter').removeClass('dnd');
        //#clr previous values
        MetaInfoValue = '';
        MetaInfo = false;

        if ($('txtBody'))
            $('txtBody').select();
    }
}

var attachCanvas = {
    toggle: function(act){
        if (act !== undefined)
        {
            if (act=='close')
            {
                $('attach_canvas_main').addClass('dnd');
                //#show toolbar: link,youtube
                $('link_attach_link').removeClass('dnd');
                $('link_attach_song').removeClass('dnd');
                $('link_attach_youtube').removeClass('dnd');
                $('link_attach_photo').removeClass('dnd');
                $('link_attach_twitter').removeClass('dnd');
            }
            else if (act=='show' || act=='')
                $('attach_canvas_main').removeClass('dnd');
        }
        else {
           if ($('attach_canvas_main'))
                $('attach_canvas_main').removeClass('dnd');
        }
    },
    twitter: function()
    {
        //#set canvas info
        attachCanvas.setinfo('Twitter connect:','attach_twitter_form');
        //#show toolbar: link,youtube
        $('link_attach_link').addClass('dnd');
        $('link_attach_song').addClass('dnd');
        $('link_attach_youtube').addClass('dnd');
        $('link_attach_photo').addClass('dnd');
        $('link_attach_twitter').addClass('dnd');
    },
    twitteraction: function()
    {
    
    },
    atphoto: function(){
        //#load upload photo
        $('frameAttachUpload').set('src','/user/views/upload.aspx?noprofilepic=0');
        //#set canvas info
        attachCanvas.setinfo('Attach photo:','attach_photo_form');
        $('link_attach_link').addClass('dnd');
        $('link_attach_song').addClass('dnd');
        $('link_attach_youtube').addClass('dnd');
        $('link_attach_photo').addClass('dnd');
        $('link_attach_twitter').addClass('dnd');
    },
    atphotoaction: function(){
        //Hide form
        if ($('attach_canvas_main'))
            $('attach_canvas_main').addClass('dnd');
        //#show toolbar: link,youtube
        $('link_attach_link').removeClass('dnd');
        $('link_attach_song').removeClass('dnd');
        $('link_attach_youtube').removeClass('dnd');
        $('link_attach_photo').removeClass('dnd');
         $('link_attach_twitter').removeClass('dnd');
    },
    link:function(){
        //#set canvas info
        attachCanvas.setinfo('Attach link:','attach_link_form');
        $('attach_link_value').set('value','');
        $('attach_link_value').focus();
        MetaInfoValue = '';
        //#show toolbar: link,youtube
        $('link_attach_link').addClass('dnd');
        $('link_attach_youtube').addClass('dnd');
        $('link_attach_photo').addClass('dnd');
         $('link_attach_twitter').addClass('dnd');
    },
    linkaction:function(){
        var dummy = $('attach_link_value').get('value');
        MetaTags.get(dummy,'1');//#retrieve url
       
        //#validate url-message to user: Notify.alert('Attach link', 'Please', 'Ok', 'red');
    },
    song:function(){
        //#set canvas info
        attachCanvas.setinfo('Search a song:','attach_song_form');        
        MetaInfoValue = '';
        //#show toolbar: link,youtube
        $('link_attach_link').addClass('dnd');
        $('link_attach_song').addClass('dnd');
        $('link_attach_youtube').addClass('dnd');
        $('link_attach_photo').addClass('dnd');
         $('link_attach_twitter').addClass('dnd');
    },
    youtube: function(){
        //#set canvas info
        attachCanvas.setinfo('Attach youtube:','attach_video_form');
        $('attach_video_value').set('value','');
        $('attach_video_value').focus();
        MetaInfoValue = '';
        //#show toolbar: link,youtube
        $('link_attach_link').addClass('dnd');
        $('link_attach_song').addClass('dnd');
        $('link_attach_youtube').addClass('dnd');
        $('link_attach_photo').addClass('dnd');
         $('link_attach_twitter').addClass('dnd');
    },
    youtubeaction: function(){ 
        var dummy = $('attach_video_value').get('value');
        MetaTags.get(dummy,'1');//#retrieve url
       
        //#validate url-message to user: Notify.alert('Attach link', 'Please', 'Ok', 'red');
    },
    sms: function(){
        //#set canvas info
        attachCanvas.setinfo('Select your SMS provider:','attach_sms_form');
    },
    location: function(){
        //#set canvas info
        attachCanvas.setinfo('Check-in:','attach_location_form');
    },
    setinfo: function(title,form){
        //#title atformOff,atformOn
        //#show canvas
        $('attach_canvas_title').set('html',title);

        if (form == 'attach_link_form')
        {
           //#show container
            if ($('attach_canvas_main').hasClass('dnd'))
                $('attach_canvas_main').removeClass('dnd');
            else
                $('attach_canvas_main').addClass('dnd');
           
            //#show form
            $(form).removeClass('dnd');
            $('attach_song_form').addClass('dnd');
            $('attach_video_form').addClass('dnd');
            $('attach_photo_form').addClass('dnd');
            $('attach_twitter_form').addClass('dnd');
        }
         if (form == 'attach_song_form')
        {
           //#show container
            if ($('attach_canvas_main').hasClass('dnd'))
                $('attach_canvas_main').removeClass('dnd');
            else
                $('attach_canvas_main').addClass('dnd');
           
            //#show form
            $(form).removeClass('dnd');
            $('attach_link_form').addClass('dnd');
            $('attach_video_form').addClass('dnd');
            $('attach_photo_form').addClass('dnd');
            $('attach_twitter_form').addClass('dnd');
        }

        if (form == 'attach_video_form')
        {
            //#show container
            if ($('attach_canvas_main').hasClass('dnd'))
                $('attach_canvas_main').removeClass('dnd');
            else
                $('attach_canvas_main').addClass('dnd');
           
            //#show form
            $(form).removeClass('dnd');
            $('attach_link_form').addClass('dnd');
            $('attach_song_form').addClass('dnd');
            $('attach_photo_form').addClass('dnd');
            $('attach_twitter_form').addClass('dnd');
            $('attach_video_form').removeClass('dnd');
        }

        if (form == 'attach_photo_form')
        {  
           //#show container
            if ($('attach_canvas_main').hasClass('dnd'))
                $('attach_canvas_main').removeClass('dnd');
            else
                $('attach_canvas_main').addClass('dnd');
           
            //#show form
            $(form).removeClass('dnd');
            $('attach_song_form').addClass('dnd');
            $('attach_video_form').addClass('dnd');
            $('attach_link_form').addClass('dnd');
            $('attach_twitter_form').addClass('dnd');
            
        }
         if (form == 'attach_twitter_form')
        {  
            //#show container
            if ($('attach_canvas_main').hasClass('dnd'))
                $('attach_canvas_main').removeClass('dnd');
            else
                $('attach_canvas_main').addClass('dnd');
           
            //#show form
             $(form).removeClass('dnd');
            $('attach_song_form').addClass('dnd');
            $('attach_photo_form').addClass('dnd');
            $('attach_video_form').addClass('dnd');
            $('attach_link_form').addClass('dnd');
            
        }

    }
}

//#Loading label drop-downs upon request
function LabelDropDown(CategoryID)
{
    var wjxDDL = new WADJAX('labels', { statusBar: false });
    var Hades = false;
    //#load once
    if ($(CategoryID + 'labelsDropdown').get('html').trim().length==0)
        Hades = true;

    if (Hades) {
        $(CategoryID + 'labelsDropdown').set('html','<div class=\"loadingDropdown\"><ul class="sub"><li><span class="loadingTop">&nbsp;</span></li></ul></div>');
        wjxDDL.send('GerLabelsDropdowns', profileInfo.ownerID, CategoryID, profileInfo.viewerID, function (res) {
                if (res.error) return;
                else {
                    $(CategoryID + 'labelsDropdown').set('html',res.value)
                    //#Attach autocomplete
                    LabelsDropDown_Events();
                    if ($(CategoryID + 'labelstextbox')) {
                        $(CategoryID + 'labelstextbox').focus();
                        $(CategoryID + 'labelstextbox').value = '';
                    }
                }
            });
    }
   
        //MylabelsDropdown
    //FollowlabelsDropdown
    //EverylabelsDropdown
}

function LabelsDropDown_Events()
{
    //---------
    //#Handle main drop-downs automplete (My, Follow, Everyone)
    //#My
    if ($('Mylabelstextbox')) {
        var tempData = JSON.decode(jsHelper.cachedData.My);
        new Meio.Autocomplete.Select($('Mylabelstextbox'), tempData, {
            selectOnTab: false, 	//
            minChars: 0,  			// The minimum number of characters the user has to input before the list of options to select is shown. 
            maxVisibleItems: 10,    // Defines the height of the list. If its 10 the list will have its height adjusted to show 10 options, but you can scroll to the other of course.
            onSelect: function (elements, value) {
                $('ulLblMy').removeClass('dnd');
                $('subAllMy').removeClass('dnd');
                if ($('subTrashMy'))
                    $('subTrashMy').removeClass('dnd');
                $('Mylabelstextbox').value = '';

                MyMenu.DropDown('Mylabels', 'inactiveMylabels', 'activeMylabels', 'MylabelsDropdown', '', '');
                //load feeds
                document.location.hash = '#!My/' + value.labelID + '/1';

            }, // this event is fired when you select an option 
            onDeselect: function (elements) {
                $('ulLblMy').addClass('dnd');
                $('subAllMy').addClass('dnd');

                if ($('subTrashMy'))
                    $('subTrashMy').addClass('dnd');
                if ($('subNew')) {
                    $('subNew').addClass('dnd');
                }
            }, // this event is fired when you deselect an option
            onNoItemToList: function (elements) {
                elements.field.node.highlight('#ff0000');
                $('ulLblMy').addClass('dnd');
                $('subAllMy').addClass('dnd');
                //if ($('subTrashMy'))
                //    $('subTrashMy').removeClass('dnd');

                if ($('subNew')) {
                    $('subNew').removeClass('dnd');
                    $('subNewtext').set('html', '' + $('Mylabelstextbox').get('value') + ' (create new)');
                }
            },
            filter: {
                type: 'contains',
                path: 'labelName'
            }/*,
            listOptions: {
                width: 300
            }*/
        }, autocompleteValues);
    }
    //#Follow
    if ($('Followlabelstextbox')) {
        var tempFData = JSON.decode(jsHelper.cachedData.Follow);
        new Meio.Autocomplete.Select($('Followlabelstextbox'), tempFData, {
            selectOnTab: false, 	//
            minChars: 0,  			// The minimum number of characters the user has to input before the list of options to select is shown. 
            maxVisibleItems: 10,    // Defines the height of the list. If its 10 the list will have its height adjusted to show 10 options, but you can scroll to the other of course.
            onSelect: function (elements, value) {
                $('ulLblFollow').removeClass('dnd');
                $('subAllFollow').removeClass('dnd');
                $('Followlabelstextbox').value = '';
                MyMenu.DropDown('Followlabels', 'inactiveFollowlabels', 'activeFollowlabels', 'FollowlabelsDropdown', '', '');
                //load feeds
                document.location.hash = '#!Follow/' + value.labelID + '/1';
            }, // this event is fired when you select an option 
            onDeselect: function (elements) {
                $('ulLblFollow').addClass('dnd');
                $('subAllFollow').addClass('dnd');
            }, // this event is fired when you deselect an option
            onNoItemToList: function (elements) {
                elements.field.node.highlight('#ff0000');
                $('ulLblFollow').removeClass('dnd');
                $('subAllFollow').removeClass('dnd');
            },
            filter: {
                type: 'contains',
                path: 'labelName'
            }
        }, autocompleteValues);
    }
    //#Everyone
    if ($('Everylabelstextbox')) {
   
        var tempEData = JSON.decode(jsHelper.cachedData.Every);
        new Meio.Autocomplete.Select($('Everylabelstextbox'), tempEData, {
            selectOnTab: false, 	//
            minChars: 0,  			// The minimum number of characters the user has to input before the list of options to select is shown. 
            maxVisibleItems: 10,     // Defines the height of the list. If its 10 the list will have its height adjusted to show 10 options, but you can scroll to the other of course.
            onSelect: function (elements, value) {
                $('ulLblEvery').removeClass('dnd');
                $('subAllEvery').removeClass('dnd');
                $('Everylabelstextbox').value = '';
                MyMenu.DropDown('Everylabels', 'inactiveEverylabels', 'activeEverylabels', 'EverylabelsDropdown', '', '');
                //load feeds
                document.location.hash = '#!Every/' + value.labelID + '/1';
                //hide menu


            }, // this event is fired when you select an option 
            onDeselect: function (elements) {
                $('ulLblEvery').addClass('dnd');
                $('subAllEvery').addClass('dnd');

            }, // this event is fired when you deselect an option
            onNoItemToList: function (elements) {
                elements.field.node.highlight('#ff0000');
                $('ulLblEvery').removeClass('dnd');
                $('subAllEvery').removeClass('dnd');
            },
            filter: {
                type: 'contains',
                path: 'labelName'
            }
        }, autocompleteValues);
    }
}
function BitLy(s) {
    if (s.indexOf('imgYouTube') > 0)
        return s; ///exclude feed content
    else {
        var initialString = s;
        var myregexp = new RegExp(/((((https?)|(ftps?)):\/\/)|(www.))[a-zA-Z0-9+&@#\/%=~\-_|$?!:.,\Z]+[.][a-zA-Z0-9+&@#\/%=~\-_|$?!:.,\Z]*[a-zA-Z0-9/]+/ig);
        var result = '';         // my match (valid url)

        var finalString = ''; //initialString;
        var temp = '';
        var startPoint = 0;
        var endPoint = 0;
        var tempString = '';
        var i = 0;
        var initialStringArray = initialString.split(' ');

        for (i = 0; i < initialStringArray.length; i++) {
            //result = myregexp.exec(initialStringArray[i]); 
            result = initialStringArray[i].match(myregexp);

            if (result != null) {
                temp = result[0].substring(0, 4).toLowerCase(); // check if http exists at start of result[0], if not add it to the url
                startPoint = initialStringArray[i].indexOf(temp, 0);
                tempString = initialStringArray[i].substring(startPoint - 6, startPoint);
                var tmp = '';
                if (tempString != 'href=\"') {
                    if (temp == 'http') {
                        tmp = result[0];
                    }
                    else {
                        tmp = 'http://' + result[0];
                    }
                    BitlyClient.shorten(tmp, 'BitlyCB.myShortenCallback');
                }
            }
        }
    }
}
//#Load Labels-My,Follow,Every
var GetLabelistData = {
    My: function(){
         var wjxGetData= new WADJAX('labels', { statusBar: false });
         try {
            wjxGetData.send('GetLabelsListData', profileInfo.ownerID,'My',profileInfo.viewerID, function (res) {
                if (res.error) return;
                else
                {
                    jsHelper.cachedData.My=res.value;
                }
            });
         }
         catch (Error) { alert('load data: ' + Error); }
    },
    Follow: function(){
         var wjxGetData= new WADJAX('labels', { statusBar: false });
         try {
            wjxGetData.send('GetLabelsListData', profileInfo.ownerID,'Follow',profileInfo.viewerID, function (res) {
                if (res.error) return;
                else
                    jsHelper.cachedData.Follow=res.value;
            });
         }
         catch (Error) { alert('load data: ' + Error); }
    },
    Every: function(){
         var wjxGetData= new WADJAX('labels', { statusBar: false });
         try {
            wjxGetData.send('GetLabelsListData', profileInfo.ownerID,'Every',profileInfo.viewerID, function (res) {
                if (res.error) return;
                else
                    jsHelper.cachedData.Every=res.value;
            });
         }
         catch (Error) { alert('load data: ' + Error); }
    }
}

//#Launch hover craft for each label
function craft_ui_reset()
{   
    $('hovercraft-mass-content').set('html',''); 
    $('hovercraft-mass-content').addClass('dnd');
    $('hovercraft-mass').setStyles({
            top: '0px',
            left: '0px'
    });
}
function craft_ui(elementID,elLabelid,elOwnerid,elFollowers,elFeeds,elhoverbody_content,elLabelName,retFollowers)
{
    elLabelName =  elLabelName.replace("\\", "");

    var hoverbody='';
    var hoverbody_share = '';
    var dummyel_pos     =  $(elementID).getCoordinates();
    
    $('hovercraft-mass').removeClass('dnd');
    $('hovercraft-mass').setStyles({
            top: dummyel_pos.top + dummyel_pos.height - 3+ 'px',
            left: dummyel_pos.left - 5 + 'px',
            position: 'absolute',
            display: 'block',
            zindex: '100000',
            display: 'block',
            height:'150px'
    });
    
    hoverbody +='<div class=\"share-arrow\">&nbsp;</div>';
    hoverbody +='<div class=\"share-body\">';
    hoverbody +='<table border=\"0\" cellpadding=\"0\"  cellspacing=\"0\">';
    if (elhoverbody_content == 'loading')
    {
        hoverbody +='<tr><td colspan=\"2\"><div class=\"f_l pad7\"><img src=\"/s3.images/ajax/colored-preloader.gif\"</div></td></tr>';
    }
    else
    {
        //#user info
        //#hoverbody +='<tr><td colspan=\"2\"><div class=\"f_l pad5\"><table border=\"0\"><tr><td style=\"vertical-align:top;\"><img alt="Prekesh Chavda" height="48" src=\"http://a2.twimg.com/profile_images/1092624226/Bobafett_normal.png\" width="48"></td><td style=\"vertical-align:top;\"><table border=\"0\"  style=\"width:200px;\"><tr><td class=\"f12\"><b>name</b></td></tr><tr><td class=\"f11\"><a href=\"\">@username</a></td></tr><tr><td class=\"f11\">Athens, Greece</td></tr></table></td></table></div></td></tr>';

        if (profileInfo.isLoggedIn)
        {
            if (parseInt(elFollowers)>0)
            {   
                hoverbody +='<tr><td class=\"f11 pad7\" colspan=\"2\"><div class=\"\"><a target=\"_blank\" href=\"/user/followers/?uid='+elOwnerid+'&labelid='+elLabelid+'\">'+ elFollowers +' followers</a></div></td></tr>';
                //hoverbody +='<tr><td class=\"f11 padL5 padT7 padB7\" colspan=\"2\">'+retFollowers+'</div></td></tr>';
            }
            else
            {
                if (elOwnerid==profileInfo.viewerID)
                    hoverbody +='<tr><td colspan=\"2\"><div class=\"f_l pad7\">0 Followers</div></td></tr>';
                else
                    hoverbody +='<tr><td colspan=\"2\"><div class=\"f_l pad7\">0 Followers</div></td></tr>';
            }
        }
        else
        {   
            if (parseInt(elFollowers)>0)
            {
                
                hoverbody +='<tr><td class=\"f11 pad7\" colspan=\"2\"><div class=\"\"><a target=\"_blank\" href=\"/user/followers/?uid='+elOwnerid+'&labelid='+elLabelid+'\">'+ elFollowers +' followers</a></div></td></tr>';
                //hoverbody +='<tr><td class=\"f11 padL5 padT7 padB7\" colspan=\"2\">'+retFollowers+'</div></td></tr>';
            }
            else
                hoverbody +='<tr><td colspan=\"2\"><div class=\"f_l pad7\">0 Followers</div></td></tr>';
        }
        //#share link-visible only when logged in
        if (profileInfo.isLoggedIn)
        {
            if (elOwnerid==profileInfo.viewerID)
                hoverbody +='<tr><td class=\"coloredBorderTop pad7 f11 share-footer cursor\" onclick=\"InviteToFollow_share(\''+elLabelid+'\',\''+elOwnerid+'\');\" colspan=\"2\"><div>Invite to follow <b>#'+elLabelName+'</b></div></td></tr>';
            else
            {
                if (jsHelper.cachedData.Follow.indexOf('"id":'+elLabelid)>=0)
                    hoverbody +='<tr><td class=\"coloredBorderTop coloredBlueBackground pad7 f11 cursor\" onclick=\"InviteToFollow_share(\''+elLabelid+'\',\''+elOwnerid+'\');\" colspan=\"2\"><div><span class=\"followersNumWhite cursor\">Share this label</span></div></td></tr>';
                else
                   hoverbody +='<tr><td class=\"coloredBorderTop pad7 f11 share-footer\" colspan=\"2\"><div><a target=\"_blank\" href=\"/sessions/landingpage.aspx?labelid='+elLabelid+'&ownerID='+elOwnerid+'\">Follow <b>#'+elLabelName+'</b></a></div></td></tr>';
            }  
        }
        else
            hoverbody +='<tr><td class=\"coloredBorderTop pad7 f11 share-footer\" colspan=\"2\"><div><a  target=\"_blank\" href=\"/sessions/landingpage.aspx?labelid='+elLabelid+'&ownerID='+elOwnerid+'\">Follow <b>#'+elLabelName+'</b></a></div></td></tr>';
     
    }
    hoverbody +='</table>';
    hoverbody +='</div>';
    //#sponsored label disabled:<tr><td class=\"coloredBorderTop coloredBackground pad5 f11\" colspan=\"2\">This is a sponsored label by <a>Wired News</a></td></tr>
    //$('hovercraft-mass').setStyle('display', 'block').fade('in');
    $('hovercraft-mass-content').set('html',''); 
    $('hovercraft-mass-content').set('html',hoverbody);
}
function craft_passengers(elLabelid,elLabelName)
{       
        var retFollowers='';
        var wjxGetlabelfollowers= new WADJAX('labels', { statusBar: false });
        wjxGetlabelfollowers.send('GetLabelFollowers',elLabelid, profileInfo.ownerID, profileInfo.viewerID, elLabelName,profileInfo.ownerWadjaID, function (res) {
            if (!res.error) {
                 retFollowers = res.value;
            }
        });
}
function launch_craft(elementID,elLabelid,elOwnerid,elLabelName)
{   
       
         //craft_ui(elementID,elLabelid,elOwnerid,'','','loading')
         var wjxGetlabelInfo= new WADJAX('labels', { statusBar: false });
         try {
                
                wjxGetlabelInfo.send('GetInfo', elLabelid, elOwnerid, function (res) {
                if (res.error) return;
                else
                {
                     var labelInfo = JSON.decode(res.value);
                     if (labelInfo!=null)
                     {
                         //if (parseInt(labelInfo.followersCount)>0)
                         //{
                         //   var wjxGetlabelfollowers= new WADJAX('labels', { statusBar: false });
                         //   wjxGetlabelfollowers.send('GetLabelFollowers',elLabelid, profileInfo.ownerID, profileInfo.viewerID, elLabelName,profileInfo.ownerWadjaID, function (res) {
                         //       if (!res.error)
                         //               craft_ui(elementID,elLabelid,elOwnerid,labelInfo.followersCount,'','',elLabelName,res.value);
                         //   });
                         //}
                         //else
                   
                         if (parseInt(labelInfo.privacy)==2)
                         {
                            craft_ui_reset();//hide if any opened overlay
                         }
                         else
                         {
                            craft_ui(elementID,elLabelid,elOwnerid,labelInfo.followersCount,'','',elLabelName,'');
                         }
                            
                     }
                }
            });
         }
         catch (Error) { alert('load data: ' + Error); }
}
//#Contacts
var Contacts = {
    Add: function(uID){
          
          var addcc = new Facebox({
                    title: 'Label ' + profileInfo.ownerWadjaID + ' as Contact?',
                    message: '<div class=\"pad5\">'+profileInfo.ownerWadjaID+' will be added to your <b>#Contact</b> label.</div>',
                    submitValue: 'Add label',
                    submitFunction: function () {
                        Contacts.AddEvent(uID);
                        addcc.close();
                    },
                    cancelValue: 'Cancel',
                    cancelFunction: function () {
                        addcc.close();
                    }
                });
                addcc.show();
    },
    AddEvent: function(uID)
    {
            wjxContacts.send('AddContact', uID, function (res) {
                if (res.error) return;
                else
                {
                    if (res.value == 'true')
                    {
                        $('contacts_link').set('html','<span  onclick=\"javascript:Contacts.Remove(\''+uID+'\');">Remove from contacts</span>');
                        $('add_remove_contact').set('html','<span title=\"Remove contact\" onclick="javascript:Contacts.Remove(\''+uID+'\');">&nbsp;</span>');
                        $('add_remove_contact').addClass('checkedicon');
                        $('add_remove_contact').removeClass('addicon');
                    }
                    else
                    {
                        var classTitle = 'faceboxTitleRed';
                        var classBorder = 'faceboxRed';
                        privacyBox = new Facebox({
                            title: 'Privacy',
                            message: '<div class="pad5">'+profileInfo.ownerWadjaID + ' has set privacy to not be labeled as a <b>#Contact</b>. <br/><a href=\"javascript:SetTextBox(\'@'+profileInfo.ownerWadjaID+'\');privacyBox.close();Postsetfocus();\">Click here</a> to send a message to this person.</div>',
                            cancelValue: 'Ok',
                            classNameTitle: classTitle,
                            classNameBorder: classBorder
                        });
                        privacyBox.show();                        
                        //Notify.alert('Privacy', '<div class="pad5">'+profileInfo.ownerWadjaID + ' has set privacy to not be labeled as a <b>#Contact</b>. <br/><a href=\"javascript:SetTextBox(\'@'+profileInfo.ownerWadjaID+'\');parent.alertBox.close();\">Click here</a> to send a message to this person.</div>', 'Ok', 'red');
                  
                    }
                }
             });
    },
    Remove: function(uID){
       
        var delcc = new Facebox({
            title: 'Remove label contact from ' + profileInfo.ownerWadjaID + '?',
            message: '<div class=\"pad5\">Are you sure you want to remove label contact from this person?</div>',
            submitValue: 'Yes, remove label',
            submitFunction: function () {
                Contacts.RemoveEvent(uID);
                delcc.close();
            },
            cancelValue: 'Cancel',
            cancelFunction: function () {
                delcc.close();
            }
        });
        delcc.show();
    },
    RemoveEvent: function(uID){
            wjxContacts.send('RemoveContact', uID, function (res) {
                if (res.error) return;
                else
                {
                    if (res.value == 'true')
                    {
                        $('contacts_link').set('html','<span onclick="javascript:Contacts.Add(\''+uID+'\');">Add to contacts</span>');
                        $('add_remove_contact').set('html','<span title=\"Add contact\"  onclick="javascript:Contacts.Add(\''+uID+'\');">&nbsp;</span>');
                        $('add_remove_contact').removeClass('checkedicon');
                        $('add_remove_contact').addClass('addicon');
                    }
                    else
                    {
                      Notify.alert('Privacy', '<div class="pad5">'+profileInfo.ownerWadjaID + ' does not accept to be labeled as contact. You can send a message to this person by typing @'+profileInfo.ownerWadjaID+'</div>', 'Ok', 'red');
                    }
                }
             });
    },
    AddFromSearch: function(contactWadjaID, contactDetailsID){
        var addfc = new Facebox({
            title: 'Label ' + contactWadjaID + ' as Contact?',
                    message: '<div class=\"pad5\">' + contactWadjaID + ' will be labeled as contact.</div>',
                    submitValue: 'Add label',
                    submitFunction: function () {
                        Contacts.AddFromSearchEvent(contactDetailsID);
                        addfc.close();
                    },
                    cancelValue: 'Cancel',
                    cancelFunction: function () {
                        addfc.close();
            }
        });
        addfc.show(); 
    },
    AddFromSearchEvent: function(contactDetailsID){
        wjxContacts.send('AddContact', contactDetailsID, true, function (res) {
                if (res.error) return;
                else
                {
                    var contactWadjaID = res.value.split('s@p@l@t')[2];
                    var contactID = res.value.split('s@p@l@t')[1];
                    var oRes=JSON.decode(res.value.split('s@p@l@t')[0]);
                    if(oRes == true){
                        $('addContact_' + contactID).addClass('dndD');

                    }
                    
                    else
                    {
                        Notify.alert('Privacy', '<div class="pad5">' + contactWadjaID + ' does not accept to be labeled as contact. You can send a message to this person by typing @' + contactWadjaID + '</div>', 'Ok', 'red');
                    }
                }
             });
    }
}
//#Compose
function ToggleSenderID(action)
{
    if (action==0)
    {
        if (senderID==0)
        {
            if (senderUID_number!='')
            {
                senderID=1;
                $('compose_from_senderID').set('html',senderUID_number);
                wProfile.Compose.SetFrom(1,senderUID_number);
                senderUID_current = senderUID_number;
            }
            else
            {
                var vermob = new Facebox({
                    title: 'Verify mobile number',
                    message: '<div class=\"pad5\">Please verify your mobile number to receive replies back to your handset.</div>',
                    submitValue: 'Ok',
                    submitFunction: function () {
                        window.location.href ='/account/mobile/';
                    },
                    cancelValue: 'Cancel',
                    cancelFunction: function () {
                        vermob.close();
                    }
                });
                vermob.show();
            }
        }
        else
        {
            senderID = 0;
            $('compose_from_senderID').set('html',senderUID);
            wProfile.Compose.SetFrom(0, senderUID);
            senderID_number= senderUID;
        }
    }
    else if (action==1)
    {
        //#When sending SMS
        $('compose_from_senderID_tip').removeClass('dnd');
    
    }
    else
    {
        $('compose_from_senderID_tip').addClass('dnd');
    }
}

//#Helper functions-Place below this line all "helper" functions and variables
var jsHelper = {
    //#Handles logo link
	logolink: function()
	{
		if ($('home_logo'))
   	 	{
//	        if (profileInfo.isLoggedIn)//#After 15 minutes attach link on logo
//	            (function () { $('home_logo').set('href', '/' + profileInfo.viewerWadjaID + '#!My/0/1'); }).delay(5 * 1000);
//	        else
	            $('home_logo').set('href', '/');
	    }
	},
	//#Handles anonymus postings coming from the homepage
	anonymuspost: function()
	{
		if (getQuerystring('labelname') != '' && getQuerystring('post') != '')
		{
       	 	var as_labelname    = getQuerystring('labelname').replace('%20',' ');
	        var as_labelpost    = getQuerystring('post').replace('%20',' ');
	        var as_labelid      = getQuerystring('labelid');
	
	        $('feed_anonymous').removeClass('dnd');
	        $('feed_anonymous_text').set('html', as_labelpost.replace('%20',' '));
	        $('feed_anonymous_link').set('html', as_labelname.replace('%20',' '));
	        $('feed_anonymous_link').set('href', '#!My/' + as_labelid + '/1');
   	 	}
	    else
	    {
	        $('feed_anonymous').addClass('dnd');
	        
	    }
	},
	//#Handle message attachments: Youtube, Photos, Links, Twitter, SMS
	attachments: function()
	{
		if ($('link_attach_link')) {
	        $('link_attach_link').addEvent('click', function (event) {
	             attachCanvas.link();
	        });
	    }
	    
	    if ($('attach_link_button')){
	        $('attach_link_button').addEvent('click', function (event) {
	             attachCanvas.linkaction();
	        });
	    }
	    
	    if ($('attach_link_value'))
	    {
	        $('attach_link_value').addEvents({
	            'focus': function (e) {
	                if ($('attach_link_value').get('value').trim() == 'http://') {
	                    $('attach_link_value').set('value', '');
	                    $('attach_link_value').removeClass('grayColor');
	                }
	                else {
	                    $('attach_link_value').removeClass('grayColor');
	                }
	            },
	            'blur': function (e) {
	                if ($('attach_link_value').get('value').trim() == '') {
	                    $('attach_link_value').set('value', 'http://');
	                    $('attach_link_value').addClass('grayColor');
	                }
	            }
	        });
	    }
        if ($('link_attach_song')) {
	        $('link_attach_song').addEvent('click', function (event) {
	             attachCanvas.song();
	        });
	    }	   
	
         if ($('link_attach_twitter')) {
	         $('link_attach_twitter').addEvent('click', function (event) {
	             attachCanvas.twitter();
	        });
	     }

         if ($('link_attach_youtube')) {
	         $('link_attach_youtube').addEvent('click', function (event) {
	             attachCanvas.youtube();
	        });
	     }

	     if ($('attach_youtube_button')){
	        $('attach_youtube_button').addEvent('click', function (event) {
	             attachCanvas.youtubeaction();
	        });
	    }
        
	    /*
	    if ($('link_attach_photo') && wProfile.Current.DetailsID == profileInfo.viewerID) {
	        $('link_attach_photo').addEvent('click', function (event) {
	             attachCanvas.photos();
	        });
	    }
	    if ($('link_attach_sms') && wProfile.Current.DetailsID == profileInfo.viewerID) {
	        $('link_attach_sms').addEvent('click', function (event) {
	             attachCanvas.sms();
	        });
	    }
	    if ($('link_attach_location') && wProfile.Current.DetailsID == profileInfo.viewerID) {
	        $('link_attach_location').addEvent('click', function (event) {
	             attachCanvas.location();
	        });
	    }
	    */
	    if ($('attach_canvas_close'))
	    { 
	        $('attach_canvas_close').addEvent('click', function (event) {
	             attachCanvas.toggle('close')
	        });
	    }
	    //#Open pop-up window for sharing photos
    	if ($('link_attach_photo') && wProfile.Current.DetailsID == profileInfo.viewerID) {
	        $('link_attach_photo').removeClass('dnd');
	        $('link_attach_photo').addEvent('click', function (event) {
	            /*PicFB = new Facebox({
	                url: '/user/views/upload.aspx?noprofilepic=0',
	                width: 400,
	                height: 200,
	                title: 'Attach a photo to this post',
	                submitValue: 'Attach',
	                submitFunction: function () {
	                    Notify.spinnerOn("Loading...", "Still loading...", 5);
	                    $i('framePhotoUpload').getElementById('formPhotoUpload').submit();
	                },
	                cancelValue: 'Cancel',
	                cancelFunction: function () {
	                    PicFB.close();
	                }
	            });
	            PicFB.show();*/
                //#use frame
                attachCanvas.atphoto();
                
	        });
	    }
        // attach youtube link when no feeds
         if ($('attach_youtube_nofeeds')) {
	         $('attach_youtube_nofeeds').addEvent('click', function (event) {
	             attachCanvas.youtube();
	        });
	     }
        // upload pic when no feeds
        if ($('upload_pic_nofeeds')) {
	        $('upload_pic_nofeeds').addEvent('click', function (event) {	           
                attachCanvas.atphoto();
                
	        });
	    }
	    //---------
        // change pic when no feeds
         if ($('change_pic_nofeeds')) {
         $('change_pic_nofeeds').addEvent('click', function (event) {
	            PicFB = new Facebox({
	                url: '/user/views/upload.aspx',
	                width: 400,
	                height: 200,
	                title: 'Change Profile Picture',
	                submitValue: 'Upload',
	                submitFunction: function () {
	                   Notify.spinnerOn("Loading...", "Still loading...", 5);
                       $i('framePhotoUpload').getElementById('formPhotoUpload').submit();
                    },
	                cancelValue: 'Cancel',
	                cancelFunction: function () {
	                    PicFB.close();
	                }
	            });
	            PicFB.show();
	        });
         }
	    //#Open pop-ip window for changing profile pic
	    if ($('dv_change_pic') && wProfile.Current.DetailsID == profileInfo.viewerID) {
	        $('dv_change_pic').removeClass('dndD');
	        $('dv_change_pic').addEvent('click', function (event) {
	            PicFB = new Facebox({
	                url: '/user/views/upload.aspx',
	                width: 400,
	                height: 200,
	                title: 'Change Profile Picture',
	                submitValue: 'Upload',
	                submitFunction: function () {
	                   Notify.spinnerOn("Loading...", "Still loading...", 5);
                       $i('framePhotoUpload').getElementById('formPhotoUpload').submit();
                    },
	                cancelValue: 'Cancel',
	                cancelFunction: function () {
	                    PicFB.close();
	                }
	            });
	            PicFB.show();
	        });
	    }
	},
    
	//#Handle new feeds bar-events e.t.c
	handlePushfeedbar: function()
	{
	  if ($('aNewFeeds')) {
	        $('aNewFeeds').addEvent('click', function (event) {
	            new Fx.Reveal($('aNewFeeds'), { duration: 500 }).dissolve();
                new Fx.Reveal($('newfeeds_wrapper'), { duration: 500 }).dissolve();
	            wProfile.Render.Start(wProfile.Helper.Pending, true);
	        });
	  }
      if ($('newfeeds_wrapper')) {
	        $('newfeeds_wrapper').addEvent('click', function (event) {
	            new Fx.Reveal($('aNewFeeds'), { duration: 500 }).dissolve();
                new Fx.Reveal($('newfeeds_wrapper'), { duration: 500 }).dissolve();
	            wProfile.Render.Start(wProfile.Helper.Pending, true);
	        });
	  }
      
	},
	//#Handle compose form send button-events e.t.c
	handleSendButton: function()
	{
		if ($('profile_compose_send')) {
        $('profile_compose_send').addEvents({
            'click': function () {
                try {
                    /// Send/Post messages and feeds
                    wProfile.Compose.Send();
                }
                catch (jsError) {
                    /// Javascript error message
                    Notify.alert('Javascript error', 'Javascript error while using [send button] #' + jsError, 'Ok', 'red');
                }
            },
            'mousedown': function () {
                /// Set button style active-clicked
                $(this.id).addClass('btn_active_submit');
            },
            'mouseup': function () {
                /// Set button style back to active
                $(this.id).removeClass('btn_active_submit');
            }
        });
      }
	},
	//#Handle twitter icon-show/hide
	handleTwitterButton: function()
	{
	 	if($('link_attach_twitter') && profileInfo.viewerID == profileInfo.ownerID) {
	        $('link_attach_twitter').removeClass('dnd');
	    }
	},
	//#Handle wadja thinking
	handleWadjaThinking: function(){
		if ($('txtTo')) {
	        $('txtTo').addEvent('keyup', function (event) {
	            wProfile.Compose.Type(event);
	        });
            $('txtTo').addEvent('focus', function (event) {
	            if($('txtTo')) {
                    if($('txtTo').hasClass('type_message')) {
                        $('txtTo').removeClass('type_message');
                        $('txtTo').value = '';
                    }
                    else {
                        $('txtTo').setCaretPosition('end');
                    }
                }
	        });
            $('txtTo').addEvent('blur', function (event) {
	            if ($('txtTo') && $('txtTo').value.trim() == '') {
                    $('txtTo').addClass('type_message');
                    $('txtTo').value = 'Type @ or + here...';
                }
	        });
	    }	
        if ($('txtBody')) {
	        $('txtBody').addEvent('keyup', function (event) {
	            wProfile.Compose.BodyType(event);
	        });
            $('txtBody').addEvent('focus', function (event) {
	            if ($('txtBody')) {
                    if($('txtBody').hasClass('type_message')) {
                        $('txtBody').removeClass('type_message');
                        $('txtBody').value = '';
                    }
                    else {
                        $('txtBody').setCaretPosition('end');
                    }
                }
	        });
            $('txtBody').addEvent('blur', function (event) {
	            if ($('txtBody') && $('txtBody').value.trim() == '') {
                    $('txtBody').addClass('type_message');
                    $('txtBody').value = 'Click here to type your message...';
                }
	        });
	    }
	},
	//#Handle search requests
	handleSearch: function()
	{
   	 	var qString     = window.location.search.substring(1); 	//!For search
	    var qsValues    = qString.parseQueryString();			//!For search
	    //---------
	    if (qsValues.searchFor != null && qsValues.searchFor.length > 0) {
	        wProfile.Search(qsValues.searchType, qsValues.searchFor);
	    }
	},
	//#Handle external feeds-from third party APIs
	handleExternalFeeds: function()
	{
	 	(function () { GetExternalFeeds.periodical(301000); }).delay(30 * 1000);
	},
	//#Handle compose form autosuggest
	handleAutosuggest: function(){
	    if ($('txtBody')) {
         bootloader.load('/user/plugins/suggest.js', function () {
            wProfile.Compose.AutoSuggest.Obj = new WadjaSuggest('txtTo', {
	            minLength: 1,
	            suggestions: wProfile.Compose.AutoSuggest.Results,
	            contains: false,
	            seperator: ' ',
	            ignored: []
	        });
         });
	    }	
	},
	//#Handle twitter connections
	handleTwitterCon: function(){
		if ($('TwitterList') && profileInfo.viewerID == profileInfo.ownerID) {
	        Twitter.empty();
	        var accountsArray = JSON.decode(MyTwitterConnections); 
	        var twList = new Element('ul');
	        for (var i = 0; i < accountsArray.length; i++) {
	            if(accountsArray[i].AutopostID == 1) TwitterAutoPost=true;
	            var liTwitter = new Element('li', { 'id': 'liTwCon_' + accountsArray[i].ConnectionID,'class':'padB5 padT5' });
	            var chbTwitter = new Element('input', {
	                'type': 'checkbox',
	                'id': 'chkTwCon_' + accountsArray[i].ConnectionID,
	                'class': 'twitterCheckBox',
	                'value': accountsArray[i].ConnectionID,
	                'checked': (accountsArray[i].AutopostID == 0 ? '' : 'checked'),
	                'events': {
	                    'click': function () {
                            
	                        // update the array that will be sent to Message class
	                        if (this.checked) {
	                            Twitter.push(parseInt(this.value));
	                        }
	                        else if (Twitter.indexOf(parseInt(this.value)) > -1) {
	                            Twitter.splice(Twitter.indexOf(parseInt(this.value)), 1);
	                        }
                            
	                        // show the appropriate Twitter icon
	                        if (Twitter.length > 0) {
	                            $('link_attach_twitter').removeClass('autoTwitter');
	                            $('link_attach_twitter').addClass('autoActiveTwitter');
	                        }
	                        else {
	                            $('link_attach_twitter').removeClass('autoActiveTwitter');
	                            $('link_attach_twitter').addClass('autoTwitter');
	                        }
	                        // save this Autopost option into the DB
	                        wjxShhProfile.send('AutoPostUpdate', profileInfo.ownerID, this.value, wProfile.Current.LabelID, this.checked, function (res) { });
	                        //cmpSilentAjax2.send('UpdateAutopostOptions', currentView.label, this.value, this.checked);
                            attachCanvas.toggle('close');
	                    }
	                }
	            });
	            // the label for each checkbox
	            var lblTwitter = new Element('label', {
	                'for': 'chkTwCon_' + accountsArray[i].ConnectionID,
	                'class': 'padL5 topM2 psRel',
	                'html': accountsArray[i].OAuthScreenName + ' (' + accountsArray[i].OAuthName + ')'
	            });
	
	            liTwitter.grab(chbTwitter);
	            liTwitter.grab(lblTwitter);
	            twList.appendChild(liTwitter);
	
	            if(!TwitterAutoPost)
	                CheckTwitterForLabel();
	            //twList.appendChild(new Element('li', { 'html': '<a href=\'javascript:UpdateAutoPost("'+accountsArray[i].ConnectionID+'");\'>'+accountsArray[i].Provider+'</a>' }));
	        }
	        $('TwitterList').appendChild(twList);
	        var twNoList = new Element('ul');
	        var liAddNewTwitter = new Element('li', { 'class': 'padT5 padB5 clearboth' });
            var spAddNewTwitter =  new Element('span', {
                'class':'coloredBackground elcloud pad10 f11 marR10 blueColor w320 dnb f_l',
	            'text': 'Connect with your Twitter account!'
	        });
	        var lnkAddNewTwitter = new Element('a', {
	            'href': '/controllers/thirdPartyConnect.ashx?provider=twitter&url=' + location.href,
                'class':'btn_submit f_l marT5',
	            'text': 'Connect',
                'target':'blank'
	        });
            liAddNewTwitter.grab(spAddNewTwitter);
	        liAddNewTwitter.grab(lnkAddNewTwitter);
	        twNoList.appendChild(liAddNewTwitter);
	        $('TwitterList').appendChild(twNoList);
	    }
	},
	//#Handle label dropdowns-autocomplete
	handleLabelDropdowns: function(){
    	//#load My data-once ondomready
	    if (jsHelper.cachedData.My.trim()=='')
	        GetLabelistData.My();
	      
	    if (jsHelper.cachedData.Every.trim()=='')
	        GetLabelistData.Every();
	     
	    if (jsHelper.cachedData.Follow.trim()=='')
	        GetLabelistData.Follow();	
	},
	//#Handle first time feeds
	handleStart: function(){
    	if (isDomReady && !document.location.hash.Contains('!') ) {
                //#star from #home
	            wProfile.Load(wProfile.Current.DetailsID, "My", 0, 1, true);
	    }	
	},
    //#Stores label's dropdown values for autocomplete ondomready
	cachedData: {
		My:'',
		Follow: '',
		Every: ''
	},
    //#Resend email verfication
    ResendConfirm: function() {
        try {
            Notify.spinnerOn('loading...', 'still loading', 5);
            oWUser.send('ResendConfirmation', function (res) {
                Notify.spinnerOff('done', 1);
                Notify.topBarOn(res.value, '', 6);
            });
        }
        catch (Error) { 
             Notify.alert('Javascript error', '<div class="pad10">ResendConfirm, #error:' + Error + '</div>', 'Ok', 'red');
         } 
    },
    //#Set dropdowns active-My, Follow, Every
    handleDropDowns: function()
    {
           //#Make active/inactive accordingly
           $$('.labelDDL').each(function (element, index) {
                    if (element.get('id').toLowerCase().indexOf(wProfile.Current.Category.toLowerCase())>=0)
                        $(element.get('id')).addClass('top-sel');
                    else
                        $(element.get('id')).removeClass('top-sel');
                });

            if (wProfile.Current.Category == 'My')
            {
                if (profileInfo.profileBelongsToViewer) {
                    $('dvFilters').removeClass('dnd');
                    $('dvFilters_sender').removeClass('dnd');
                }
                else
                    $('dvFilters_sender').addClass('dnd');
            }
            else
               $('dvFilters').addClass('dnd'); 
    },
    //#Handle custom profile settings
    handleCustomprofiles: function()
    {
        if (profileInfo.ownerWadjaID == 'wadja')
        {
            //#hides drop-downs My, Follow, Every
            $('Mylabels').addClass('dnd');$('Followlabels').addClass('dnd');$('spaceFollowlabels').addClass('dnd');$('Everylabels').addClass('top-sel');
        }
    },
    //#Reset search elements
    resetSearchElements: function()
    {
        $('srch_feeds').empty(); $('srch_labels').empty();$('srch_users').empty();$('srch_web').empty();$('master_feeds_container').removeClass('dnd');$('search_feeds_container').addClass('dnd');$('dvFilters_search').addClass('dnd');
    },
    //#Reset filters
    resetFilters: function()
    {
       $('privacyicon_1').set('class', 'tofromImageDr');
       wProfile.Current.Filter = 0;
    }
}

/* String Prototype Overrides */
String.prototype.replaceAll = function (s, r) { return (r === undefined ? this : this.split(s).join(r)); } /* Replace all instances in String */

//#Handles Contact functions
var Contact= {
	Save: function(contactID)
	{
        var firstname = '';
        var lastname = '';
        var url = '';
        var email = '';
        var mobile = '';
        var gender = '';
        var dob;
        if($('contact_firstname_'+contactID))
            firstname=$('contact_firstname_'+contactID).value;
        if($('contact_lastname_'+contactID))
            lastname=$('contact_lastname_'+contactID).value;
        if($('contact_url_'+contactID))
            url=$('contact_url_'+contactID).value;
        if($('contact_email_'+contactID))
            email=$('contact_email_'+contactID).value;
        if($('contact_mobile_'+contactID))
            mobile=$('contact_mobile_'+contactID).value;
        if($('contact_day_'+contactID) && $('contact_month_'+contactID) && $('contact_year_'+contactID)) {
            dob=$('contact_year_'+contactID).value+'/'+$('contact_month_'+contactID).value+'/'+$('contact_day_'+contactID).value;
        }
        if($('contact_gender_'+contactID))
            gender=$('contact_gender_'+contactID).value;
        wjxContacts.send('Update',contactID,firstname,lastname,email,dob,gender,mobile,url, function(res) {
            if(res.error != null) return;
            
            var oRes=JSON.decode(res.value);
            if(oRes.DetailsID>0) {
                Notify.topBarOn("Your contact has been updated", '', 5);

                var feedText = '';
                var location = '&nbsp;-&nbsp;' + oRes.Location;
                var name = oRes.Name;
                
                var m = oRes.Birthday.match(/^\/Date\(([-+])?(\d+)([-+]\d\d)?(\d\d)\)\/$/);
                var date = null;
                if (m) {
                    var sign=1;
                    if(m[1] != undefined && m[1] == '-')
                        sign=-1;
                    var timestamp = m[2];
                    var timezone = 0;
                    if(m[3] == undefined)
                        timestamp += m[4];
                    else
                        timezone = 3600000*m[3] + 60000*m[4]
                    var dt = sign*timestamp + timezone;
                    //date = new Date(dt).format('%B %d, %Y');
                    date = new Date(dt);
                    var m_names = new Array("January", "February", "March", 
                        "April", "May", "June", "July", "August", "September", 
                        "October", "November", "December");
                    var dateMonth=m_names[date.getMonth()];
                    var stringDate = dateMonth + ' ' + date.getDate() + ', '+ date.getFullYear();
                }

                var born = '&nbsp;-&nbsp;' + stringDate;
                var url = '';
                if(oRes.URL != null)
                    url = '&nbsp;-&nbsp;' + wProfile.Render.Links(oRes.URL);
                
                var email = '';
                if (email != null && email.length != 0)
                    feedText = '<span class=\"f_l \">' + name + '</span><span class=\"f_l \">' + born + '</span><span class=\"f_l\">' + location + '</span><span class=\"f_l \">' + url + '</span><span class=\"f_l\">&nbsp;-&nbsp;<a href=\"' + email + '\" target=\"_blank\">' + email + '</a></span>';
                else
                    feedText = '<span class=\"f_l \">' + name + '</span><span class=\"f_l \">' + born + '</span><span class=\"f_l\">' + location + '</span><span class=\"f_l \">' + url + '</span>';
                if($('spnText'+oRes.DetailsID))
                    $('spnText'+oRes.DetailsID).set('html',feedText);
            }
        });
    }
}

//#used by the compose form for counting rows
function countLines(strtocount, cols) {
  var hard_lines = 1;
  var last = 0;
  while ( true ) {
    last = strtocount.indexOf("\n", last+1);
    hard_lines ++;
    if ( last == -1 ) break;
  }
  var soft_lines = Math.round(strtocount.length / (cols-1));
  var hard = eval("hard_lines  " + unescape("%3e") + "soft_lines;");
  if ( hard ) soft_lines = hard_lines;
  return soft_lines;
}

//#Group drop-downs
var group = {
    label: function(labelID){
        $('group_'+labelID).toggleClass('groupDown');
        $('group_'+labelID).toggleClass('groupUp');

        $$('.grouplist_'+labelID).each(function (element, index) {
                  $(element.get('id')).toggleClass('dndD');
        });
        return;
    }
}

//#handles the compose right overlay
var ComposeOverlay= {
	Show: function() {
        var SendHover;
        if ($('send_hovercraft')) {
            SendHover = $('send_hovercraft');
            SendHover.setStyle('display', 'block').fade('in');
            SendHover.setStyles({
                top: '71px',
                zindex: '100',
                width: '290px',
                right: '3px'
            });
        }        
    },
    Hide: function() {
        var SendHover;
        if ($('send_hovercraft')) {
            SendHover = $('send_hovercraft');
            SendHover.fade('out');
            SendHover.setStyles({
                zindex: '-1'
            });
        }   
    },
    SetText: function(text, isSMS) {
        var SendHover;
        if ($('send_hovercraft')) {
            SendHover = $('send_hovercraft');
            SendHover.innerHTML = '<div class=\"share-arrow-post\" id=\"send_hovercraft_arrow\">&nbsp;</div><div class=\"body\" id=\"send_hovercraft_div\"><div>'+text+'</div><div class=\"closePost\"><span id=\"getMorePoints\" class=\"f_l lnk f11 bolt dnd\" onclick=\"OpenNewCart();\">Get more points</span><a class=\"f_r\" href=\"javascript:ComposeOverlay.Hide();\">Close <span class=\"closeIcon\">&nbsp;</span></a></div></div>';
        }   
        if(isSMS) {
                if($('send_hovercraft_div'))
                $('send_hovercraft_div').addClass('sms');
                if($('send_hovercraft_arrow')) {               
                $('send_hovercraft_arrow').removeClass('share-arrow-post');
                $('send_hovercraft_arrow').addClass('share-arrow-sms');
                }
                if($('getMorePoints'))
                $('getMorePoints').removeClass('dnd');
        }
        else {if($('send_hovercraft_div'))
                $('send_hovercraft_div').removeClass('sms');
                if($('send_hovercraft_arrow')) {
                $('send_hovercraft_arrow').removeClass('share-arrow-sms');
                $('send_hovercraft_arrow').addClass('share-arrow-post');
                }
                if($('getMorePoints'))
                $('getMorePoints').addClass('dnd');
                 }
    }
}

//#used by the get this conversation started form for posting a message
function firstPost() {
    if($('txtTo')) {
        $('txtTo').removeClass('dndD');
        setTxtBodyText();
    }
    if($('txtBody')) {
        $('txtBody').focus();
    }
}
function Postsetfocus() 
{
if($('txtBody')) {
        $('txtBody').focus();
    }
}

//#switch between views
function SwitchView(view)
{  
    UIView = view;
    //#clear content
    wHtmlCanvas.empty();
    //#load new content
    jsHelper.handleStart();	
}