/*
 * Random, small-ish JS functions for Mixcity
 */

function show_block(id)
{
	if (document.getElementById(id).style.display=="none")
		document.getElementById(id).style.display="block";
	else
		document.getElementById(id).style.display="none";
}
//use for save search paremtere on search page
//NOTE: be carefull, we set error message as param to function!!!!
function save_search_criteria(error_message)
{
	var search_name = $('SearchSearchName').value;
	if (search_name  != '')
	{
		new Ajax.Updater('action_complete','/profiles/save_search',
			{method:'post',
		    	onSuccess: function(){
					show_block("save"); // this will hide save block 
            },
			parameters: {search_name: search_name, form_data: $('searchformid').serialize()}} );
	}
	else
		alert (error_message);

}

/*
 * Wrapper function used by iframes to open windows
 */
function mcOpenWrap (win,url,name,features)
{
    if(win == null)
    {
        win = window;
    }
    var opened = window.open(url,name,features);
    opened.parent = win;
    opened.top = win.top;
}

/*
 * Wrapper function that opens url inside a floating ajax window
 */

function openIfWin (url,title, id)
{
    var win = new Window({className: "alphacube", id: id, title: title, width:400, height:350, destroyOnClose: true, recenterAuto:false, url: url});
    win.showCenter();
}

/*
 * Hides the modalbox if it is visible
 */
function hideModal ()
{
    try
    {
        Modalbox.hide();
    } catch(e) { };
    return true;
}

/*
 * This gets a safe height, no higher than max, but it can be
 * smaller if the screen size dictates it
 */
function getSafeHeight (max)
{
    if(window.innerHeight <= max)
    {
        var result = window.innerHeight;
        result = result - 25;
        return result;
    }
    return max;
}

/*
 * ***
 * Polling functions
 * ***
 */
var POLLING_INTERVAL = 30000; // 30 seconds
var currentPollTimer = null;

function pollCounter (first)
{
    if (!first)
    {
        try
        {
            performPoll();
        } catch(e) { } ;
    }
    currentPollTimer = setTimeout('pollCounter(false);',POLLING_INTERVAL);
}

function resetPollTimer ()
{
    try
    {
        clearTimeout(currentPollTimer);
    } catch(e) { };

    pollCounter(true);
}

function performPoll ()
{
    new Ajax.Request('/profiles/poll', {
        method:'get',
        onSuccess: pollReply
        }
    );
}

function pollReply (transport)
{
    var json = transport.responseText.evalJSON(true);

    if(json.response != 'OK')
        return;

    var unreadMessages = 0;
    var pendingRequests = 0;

    //set default values
    var prevGroupsInvites = 0;
    var invitedGroupCount = 0;
    var prevGroupsRequests = 0;
    var pendingGroupRequestsCount = 0;
    
    var prevMessages = $('unreadMessagesCount').innerHTML.replace(/\D/g,'');
    var prevRequests = $('pendingRequestsCount').innerHTML.replace(/\D/g,'');

    if ( $('pendingGroupRequestsCount') != undefined)
    {
        prevGroupsRequests = $('pendingGroupRequestsCount').innerHTML.replace(/\D/g,'');
    }
    if ( $('invitedGroupCount') != undefined)
    {
        prevGroupsInvites = $('invitedGroupCount').innerHTML.replace(/\D/g,'');
    }

    if(prevMessages == '')
        prevMessages = 0;
    if(prevRequests == '')
        prevRequests = 0;
    if(prevGroupsRequests == '')
        prevGroupsRequests = 0;
    if(prevGroupsInvites == '')
        prevGroupsInvites = 0;

    if(/^\d*$/.match(json.unreadMessagesCount) && json.unreadMessagesCount > 0)
        unreadMessages = json.unreadMessagesCount;

    if(/^\d*$/.match(json.pendingRequestsCount) && json.pendingRequestsCount > 0)
        pendingRequests = json.pendingRequestsCount;

    if(/^\d*$/.match(json.pendingGroupRequestsCount) && json.pendingGroupRequestsCount > 0)
        pendingGroupRequestsCount = json.pendingGroupRequestsCount;

    if(/^\d*$/.match(json.invitedGroupCount) && json.invitedGroupCount > 0)
        invitedGroupCount = json.invitedGroupCount;

    if(prevMessages != unreadMessages || prevRequests != pendingRequests || prevGroupsRequests != pendingGroupRequestsCount || prevGroupsInvites  != invitedGroupCount)
     {
        updateSidebar();
     }
    if ( (!json.hasActiveProfile) || $('profile_id').value != json.activeProfile)
    {
        updateOnProfileChange();
    }
}

function updateSidebar ()
{
     new Ajax.Updater('sidebar_top','/profiles/reqAndInbox', {asynchronous:true, evalScripts:true});
}

function updateOnProfileChange ()
{
    new Ajax.Updater('header','/profiles/updatedHeader', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'header']});
    new Ajax.Updater('dynamicWindow','/profiles/updatedChat', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'dynamicWindow']});
}

function updateOnProfileCreate ()
{
    var url = '/profiles/updatedHeader';
    var pars = '';
    var myAjax = new Ajax.Request(
        url,
        {
                method: 'post',
                parameters: {},
                onComplete: updateMenu
        });
}

function updateMenu(originalRequest)
{
    $("main_menu").update("");
    $("main_menu").update(originalRequest.responseText);
}


function updateMessageList() {
    var parent_doc = window.parent.document;

    if (parent_doc.getElementById('controllerContent') != undefined)
        new Ajax.Updater(parent_doc.getElementById('controllerContent'),"/messages", {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", parent_doc.getElementById('controllerContent')]});
    
}

function checkTiny(msg) {
    var text=tinyMCE.activeEditor.getContent();
    //check if nothing entered in tiny
    if (!text.blank())
        return true;
    else
        $("action_complete").update('<p class="message-error">'+msg+'</p>');
    return false;
}

function cleanXHTML (id, html) {
    var modify = '';
    var a = html.match(/<a[^>]*>/gi);

    if (a != null)
    {
        for (var i=0; i<a.length; i++)
        {
            modify = a[i].replace(/target="_blank"/gi, 'onclick="window.open(this.href); return false;"');
            html = html.replace(a[i], modify);
        }
    }
    return html.replace(/<br>/, '<br />');
}


function updateWallList(profile_id, type)
{
	new Ajax.Updater("wall_list","/walls/index/"+ profile_id + "/" + type+ "/"+"part" , {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", "wall_list"]});
}

function updateCommentsList(item_id, item_type) {
	//new Ajax.Updater("controllerContent", "/comments/index/"+ item_id + "/" + item_type , {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", "controllerContent"]});
    var parent_doc = window.parent.document;
    var param;
    
    
    if (parent_doc.getElementById('controllerContent') != undefined)
    {
        if (parent_doc.getElementById('comments_list_title_'+ item_id) != undefined && hasClass(parent_doc.getElementById('comments_list_title_'+ item_id), 'short_list'))
        {
            param = "short";
        }
        else
            param = "full";
        elem = parent_doc.getElementById('comments_list_'+ item_id);
        if (elem != undefined)
        {
            new Ajax.Updater(elem,"/comments/index/"+item_id + "/" + item_type + "/" +param, {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", elem]});
           //small timeout
            window.setTimeout(closePopupById('comment_win_'+item_id), 3000);
            
        }
    }
}

function updateConversation (conversation_id)
{
    page_num = $('page_num').value;
    if (page_num =='')
        page_num = 1;

    new Ajax.Updater("conversation_data_" + conversation_id, "/messages/refresh/"+ conversation_id + "/" + page_num, {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", "conversation_data_" + conversation_id]});
}

function animate_message_popup_title(conversation_id)
{
    parent_doc = window.parent.document;
    parent_doc.getElementById('message_win_'+ conversation_id +'_top').addClassName('conv_not_readed');
    parent_doc.getElementById('message_win_'+ conversation_id +'_top').toggleClassName('conv_red');
}

function markAsRead(conversation_id) {
    //markConversationAsRead
    parent_doc = window.parent.document;
    if (parent_doc.getElementById('message_win_'+ conversation_id +'_top').hasClassName('conv_not_readed'))
    {
    new Ajax.Request("/messages/markConversationAsRead/"+ conversation_id, {
        onComplete: function() {
                parent_doc.getElementById('message_win_'+ conversation_id +'_top').removeClassName('conv_not_readed');
                parent_doc.getElementById('message_win_'+ conversation_id +'_top').removeClassName('conv_red');
            }
        });
    }
}
function closePopupById(id)
{
    window.parent.Windows.close(id);
}

function updateCommentsCount(item_id, item_type) {
    var parent_doc = window.parent.document;

    if (parent_doc.getElementById('controllerContent') != undefined)
    {
        elem = parent_doc.getElementById('comments_count_'+ item_id);
        new Ajax.Updater(elem,"/comments/countcomments/"+item_id + "/" + item_type, {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", elem]});
    }
}

function checkCommentEmpty(elem, msg) {
    var text = $F(elem); //getting textarea values
    if (!text.blank())
        return true;
    else
        $("comment_complete").update('<p class="message-error">'+msg+'</p>');
    return false;
}

var cur_selected = null;
function addCommentForm(item_id)
{
show_block("commentFormBlock");
$('action_complete').update();
Form.Element.setValue('comment_item_id', item_id);
cur_selected = item_id;
 return false;
}

function show_comments(item_id, item_type) {
    id = 'comments_list_'+item_id;

 	if ((document.getElementById(id).style.display=="none") || (document.getElementById(id).style.display =='') || (document.getElementById(id).style.display == 'undefined'))
     {
        new Ajax.Updater("comments_list_"+item_id, "/comments/index/"+ item_id + "/" + item_type + "/full" , {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", "comments_list_"+item_id]});
		document.getElementById(id).style.display="block";
     }
	else
		document.getElementById(id).style.display="none";
}

function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function changeImage (img_src, image_id)
{
  $('bigImg').src=img_src;
 new Ajax.Updater("comments_holder", "/photos/commentsBlock/"+ image_id +  "/short" , {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", "comments_holder"]});
}

function getprofilepics (profile_id)
{
    
    if (document.getElementById('image_store') == undefined)
    {
        var parent_el = $('lightbox');
        var my_div = document.createElement('div');
        my_div.addClassName('pending');
        my_div.setAttribute('id', 'image_store');
       // parent_el.appendChild(my_div);
       parent_el.insertBefore(my_div, parent_el.firstChild);

    }
    new Ajax.Updater("image_store","/photos/getthumbs/"+ profile_id , {asynchronous:true, evalScripts:true, requestHeaders:["X-Update", "image_store"]});
}

function minimizeSearch ( minimize_caption, restore_caption) {
Effect.toggle('search_form', 'slide',{ duration: 0.2 });
        if($('link_caption').innerHTML.toLowerCase() == minimize_caption.toLowerCase())
            $('link_caption').update(restore_caption);
        else
            $('link_caption').update(minimize_caption);
    return false;
}

//hide search form by default for search online users
function minimizeSearchForm(restore_caption)
{
      $('search_form').hide();
      $('link_caption').update(restore_caption);
}