﻿var queueChecker = null;
var cAlertDOM = null;
var messagesQueue = null;
var alertsQueue = null;
var queueTimer = null;
var pause = null;
var notifyDlg = null;
var fadeInPanel;
var fadeOutPanel;

var tryLoginActivated = false;

function userCallsLoaded()
{
    
    modalLoaded();
    
    
    
    callsLoaded();
    
    messagesQueue = new Queue();
    alertsQueue = new Queue();
    
    messageTitle = 
    {
        privateMessage : 'Nova privatna poruka',
        friendshipRequest : 'Novi zahtjev za prijateljstvom',
        exceptionMessage : 'Sistemska poruka'
    }
    
    messageAlertType = 
    {
        privateMessage: 1,
        friendshipRequest: 2,
        exceptionMessage: 3
    }
    
    messageIcon = 
    {
        privateMessageIcon : 'url(../img/messengerNewPm.gif)',
        friendshipIcon : 'url(../img/messengerNewBuddy.gif)',
        exceptionIcon : 'url(../img/messengerWarning.gif)'
    }
    
    notifyDlg = $find('Notifier');
    if(Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version == 6) //IE FIX
    {
        notifyDlg.add_showing(setNotifyPanelPosIE6);
    }
    
    
    notifyPanelLoaded();
    
    sendPMLoaded();
    
    $addHandler(window, 'resize', onWinResized);
    
    var bannerTop = $get("bannerTop");
    
    if(bannerTop && bannerTop.offsetHeight < 10)
        bannerTop.style.display = "none";
    
    var bannerRight = $get("bannerRight");
    
    if(bannerRight && bannerRight.offsetHeight < 10)
        bannerRight.style.display = "none";
    
}

function setNotifyPanelPosIE6()
{
    notifyDlg.get_element().parentNode.style.position= 'absolute';
    notifyDlg.get_element().parentNode.style.left = (document.body.clientWidth - 260).toString() + "px";
    notifyDlg.get_element().parentNode.style.top = (document.documentElement.clientHeight + document.documentElement.scrollTop - 100 ).toString() + "px";
    notifyDlg.get_element().parentNode.style.width = 245 + 'px';
    notifyDlg.get_element().parentNode.style.height = 82 + 'px';
    notifyDlg.get_element().parentNode.style.overflow = 'hidden';
}

function userCallsUnLoaded()
{
    callsUnloaded();
    notifyPanelUnLoaded();
    
    $removeHandler(window, 'resize', onWinResized);
}

function callsLoaded() 
{
    $addHandler(document.body,'keydown',keyPressHandler);
    $addHandler($get('search'),'focus',setSearchFocus);
    
    var dlg = $find('logDialog');
    if(isAnonymous() && dlg)
        {
            dlg.add_hiding(function(){submitFunction=null;activeModalDialog=null;});
            dlg.add_showing(function(){activeModalDialog='logDialog'; });
        }

    
        var comboSearch =  $find(comboSearchCondId);
        if (comboSearch) {
            setComboBoxOptionsCollection();
            comboSearch.get_items().getItem(0).select();


            if (tSection != null)
                comboSearch.get_items().getItem(tSection).select();

        }
        
        friendsLoaded();        
}

function setSearchFocus(args)
{
    submitFunction = GoSearch; 

    if(!shown) 
    {
        showSearchPanel();
        
        var searchBounds =  Sys.UI.DomElement.getBounds($get('search'));
        //top banner fix
        var searchPanelWrapper = $get('searchPanelWrapper');
        searchPanelWrapper.style.top =searchBounds.y + 22 + 'px'; // + Sys.UI.DomElement.getBounds($get('header')).y + 22 + 'px';
        searchPanelWrapper.style.left = searchBounds.x + 'px';
        $get(searchPanelId).style.top = -50 + 'px';
        searchPanelSlide('show');
    }
}

function onWinResized()
{
    var sbox = $find("searchPanel");
    if(sbox)
    {
        sbox.hide();
        shown = false;
       $get("search").blur();
    }
}

function equaliseColumns(columnsArr)
{
    if(columnsArr.length < 1)
        return;
    
    var maxH = $get(columnsArr[0]).offsetHeight;
        
    for(var i = 0 ; i < columnsArr.length ; i++)
    {
        if($get(columnsArr[i]).offsetHeight > maxH)
            maxH = $get(columnsArr[i]).offsetHeight;
    }
    
    for(var i = 0 ; i < columnsArr.length ; i++)
    {
        $get(columnsArr[i]).style.height = maxH + 'px';
    }
}

function callsUnloaded()
{
    $removeHandler(document.body,'keydown',keyPressHandler);
    $removeHandler($get('search'),'focus',setSearchFocus);
}

function keyPressHandler(args)
{
    var k = args.keyCode ? args.keyCode : args.rawEvent.keyCode;
    if (k === Sys.UI.Key.enter)
        {
            if(submitFunction != null)
            {
                submitFunction();
                args.preventDefault();
            }
        }
    if (k === Sys.UI.Key.esc)
        {
            if(activeModalDialog != null)
            {
                $find(activeModalDialog).hide();
                args.preventDefault();
            }
        }
}


function setDialog(action, customMessage)
{
    switch(action)
    {
        case 'login':
        var msg = $get('lgnMsgs');
        msg.style.display='none';
        $get('tbLogin').value='';
        $get('tbPassword').value='';
        $get('LoginDialog').style.display='block';
        $get('Reg').style.display = 'none';
        $get('Lgn').style.display = 'block';
        $get('passRetSec').style.display = 'none'; 
        $get('loginSec').style.display = 'block';
        $get('retDescPnl').style.display = 'none';
        $get('retDescTtl').style.display = 'none';
        $get('lgnDescPnl').style.display = 'block';
        $get('lgnDescTtl').style.display = 'block';
        $get('retLnk').style.display = 'inline'; 
        $get('lLnk').style.display = 'none'; 
        $get('tbLogin').focus();
        
        submitFunction = loginSubmit;
        
        if(customMessage)
        {
             msg.style.display='block';
             msg.innerHTML = customMessage;
        }
        
        break;
    
    case 'register':
        $get('Reg').style.display = 'block';
        $get('Lgn').style.display = 'none';
        submitFunction= $get('fiz').checked ? sendRegistration : sendRegistrationLeg;
        $get('Reg').style.display = 'block';
        $get('Lgn').style.display = 'none';
        break;
        
    case 'forgottenPassword' : 
        submitFunction=passwordRetrieve;
        $get('retDescPnl').style.display = 'block';
        $get('retDescTtl').style.display = 'block';
        $get('lgnDescPnl').style.display = 'none';
        $get('lgnDescTtl').style.display = 'none';
        $get('loginSec').style.display = 'none';
        $get('passRetSec').style.display = 'block'; 
        $get('retLnk').style.display = 'none'; 
        $get('lLnk').style.display = 'inline'; 
        
        break;
    }
}

function showUserModal(action, customMessage)
{
    var dlg = $find('logDialog');
    
    if(dlg)
    {
        setDialog(action, customMessage);
        dlg.show();
    }
}

function tryLoginCallback(response)
{
    
    switch(response)
    {
        //all fine
        case 0:
            var datehash = (new Date()).valueOf();
            location.href = currUrl.indexOf('?') != -1 ? currUrl + '&rnd=' + datehash : currUrl + '?rnd=' + datehash;
        break;
        case 1:
            $get('lgnMsgs').innerHTML = 'Pogrešna username/password kombinacija';
            $get('lgnMsgs').style.display = 'block';
        break;
        case 2:
            $get('lgnMsgs').innerHTML = 'Korisnik još nije odobren od strane administratora';
            $get('lgnMsgs').style.display = 'block';
        break;
        default:
            $get('lgnMsgs').innerHTML = 'Došlo je do pogreške';
            $get('lgnMsgs').style.display = 'block';
        break;
    }
    
    tryLoginActivated = false;
}

function tryLoginFailure(response, args, userID)
{
     tryLoginActivated = false;
     onFailure(response, args, userID);

}

function passRetCallback(response)
{
    switch(response)
    {
        //all fine
        case 3:
            $get('lgnMsgs').innerHTML = 'Nova zaporka Vam je poslana na mail';
            $get('lgnMsgs').style.display = 'block';
            $get('lgnMsgs').style.color = '#FF6600';
        break;
        default:
            $get('lgnMsgs').innerHTML = 'Neispravan e-mail.';
            $get('lgnMsgs').style.display = 'block';
        break;
    }
}

function registerUser(response)
{
    switch(response)
    {
        //all fine
        
        case 0:
        case 1:
        case 2:
     
        case 3:
            return;
            break;
            
        case 4:
            $get('regMsgs').innerHTML = 'Na e-mail Vam je poslan link za potvrdu registracije.';
        break;
        
        case 5:
            $get('regMsgs').innerHTML = 'Neispravan e-mail.';
        break;
        
        case 6:
            $get('regMsgs').innerHTML = 'Zaporka je prekratka.';
        break;
        
        case 7:
            $get('regMsgs').innerHTML = 'Zaporke nisu jednake.';
        break;
        
        case 8:
            $get('regMsgs').innerHTML = 'Korisničko ime već postoji.';
        break;
        
        case 9:
            $get('regMsgs').innerHTML = 'Korisničko ime može imati najviše 10 znakova.';
        break;
        
        case 10:
            $get('regMsgs').innerHTML = 'Unešena mail adresa se već koristi na portalu.';
        break;
        
        case 12:
            $get('regMsgs').innerHTML = 'Korisničko ime sadrži nedozvoljne znakove.';
        break;
        
        case 13:
            $get('regMsgs').innerHTML = 'Korisničko ime treba imati najmanje 3 znaka.';
        break;
        
        
        default:
            $get('regMsgs').innerHTML = 'Dogodila se greška.';
        break;
    }
    
      $get('regMsgs').style.display = 'block';
      
}

//### Search Combo boxes functions START ### 
var shown = false;
var first = true;

function searchPanelSlide(action)
{
  
    var callback = null;
    var searchSlideDOM = null;
    var hide = false;
    searchSlideDOM = $get(searchPanelId);
    
    switch(action)
    {
        case 'hide':
            endPos = -75;
            shown = false;
        break;
        case 'show':
            searchSlideDOM.parentNode.style.visibility = 'visible';
            searchSlideDOM.parentNode.style.display = 'block';
            endPos = first ? 50 : 50;
            shown = true;
            first = false;
        break;
    }
    
       
       var bounds = Sys.UI.DomElement.getBounds(searchSlideDOM);

        animCalendar = new AjaxControlToolkit.Animation.MoveAnimation(searchSlideDOM, 0.2, 25, bounds.width, endPos, true , 'px');
        
        if(action == 'hide')
            animCalendar.add_ended(hidePanel);
            
        animCalendar.play();
}

function hidePanel()
{
    var searchSlideDOM = $get(searchPanelId);
    searchSlideDOM.parentNode.style.visibility = 'hidden';
    searchSlideDOM.parentNode.style.display = 'none';
    shown = false;
}

function setComboBoxOptionsCollection()
{
    var searchCombo = $find(comboSearchId);
    var searchCondCombo = $find(comboSearchCondId);
    
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Poslovni dnevnik");
    cOpt.set_value("1");
    searchCondCombo.get_items().add(cOpt); 
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Poslovni forum");
    cOpt.set_value("2");
    searchCondCombo.get_items().add(cOpt);
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Poslovna knjižara");
    cOpt.set_value("3");
    searchCondCombo.get_items().add(cOpt);
    
    comboOptions[1] = new Array();
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Sve");
    cOpt.set_value("0");
    comboOptions[1].push(cOpt);
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Naslov");
    cOpt.set_value("1");
    comboOptions[1].push(cOpt);
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Autor");
    cOpt.set_value("2");
    comboOptions[1].push(cOpt);
    
    comboOptions[2] = new Array();
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Postovi");
    cOpt.set_value("0");
    comboOptions[2].push(cOpt);
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Naziv teme");
    cOpt.set_value("1");
    comboOptions[2].push(cOpt);
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Autor");
    cOpt.set_value("2");
    comboOptions[2].push(cOpt);

    comboOptions[3] = new Array();
    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
    cOpt.set_text("Sve kategorije proizvoda");
    cOpt.set_value("0");
    comboOptions[3].push(cOpt);
// staro    
//    comboOptions[3] = new Array();
//    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
//    cOpt.set_text("Naslov");
//    cOpt.set_value("0");
//    comboOptions[3].push(cOpt);
//    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
//    cOpt.set_text("Autor");
//    cOpt.set_value("1");
//    comboOptions[3].push(cOpt);
//    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
//    cOpt.set_text("Izdavač");
//    cOpt.set_value("2");
//    comboOptions[3].push(cOpt);
//    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
//    cOpt.set_text("Naslov izvornika");
//    cOpt.set_value("3");
//    comboOptions[3].push(cOpt);
//    var cOpt = new Telerik.Web.UI.RadComboBoxItem();
//    cOpt.set_text("ISBN/ISSN");
//    cOpt.set_value("4");
//    comboOptions[3].push(cOpt);
}

function searchCondFocused(combo, args)
{
    if(combo.get_text() == " unesi ticker..")
        combo.set_text("");
}

function searchCondSelected(combo, args)
{
    var searchCombo = $find(comboSearchId);
    searchCombo.get_items().clear();
    var oColl = comboOptions[parseInt(combo.get_selectedItem().get_value())];

    if (oColl.length <= 1) {
        searchCombo.set_visible(false);
    }
    else
        searchCombo.set_visible(true);

    for(var i = 0 ; i < oColl.length ; i++)
    {
        searchCombo.get_items().add(oColl[i]);
    }
    if(searchCombo.get_items().get_count() > 0)
        searchCombo.get_items().getItem(0).select();
    comboSearchCondSelValue = combo.get_selectedItem();
}

function searchSelected(combo, args)
{
    comboSearchSelValue = combo.get_selectedItem();
}

function GoSearch()
{
   var kat = comboSearchCondSelValue.get_value();
   var searchBy = comboSearchSelValue.get_value();
   var location = httpRoot;
   var q = document.getElementById('search').value;
   
   if(q.length <3)
   {
    alert('Pojam pretraživanja mora sadržavati najmanje 3 znaka.');
    return;
   }
  
   switch(parseInt(kat))
   {
        case 1:
            if(searchBy=="2")
            {
                 location += "Content/Search.aspx?author=" + q;
            }
            else
            {
                location += "Content/Search.aspx?q=" + q + "&f5=0";
                if(searchBy=="1")
                    location += "&t=1";
            }
            break;
            
       case 2:
            if(searchBy=="0")
            {
                location += "Content/ForumSearch.aspx?q=" + q + "&f5=0";
            }
            else if(searchBy=="1")
            {
                location += "Content/ForumSearch.aspx?q=" + q + "&f5=0&a=1";
            }
            else if(searchBy=="2")
            {
                location += "Content/ForumSearch.aspx?q=" + q + "&f5=0&a=1";
            }
            break;

        case 3:
            location = "http://shop.poslovni.hr/Content/Search.aspx?t=" + q + "&g=" + searchBy;
// stara spika
//            if(searchBy == "0")
//            {
//                location += "Content/ShopSearch.aspx?q=" + q + "&n=1";
//            }
//            else
//            {
//                location += "Content/ShopSearch.aspx?q=" + q + "&n=0&f=" + searchBy;
//            }
            break;
        
        case 4:
            location += "Content/Search.aspx?q=" + q;
            break;
    }
    if (parseInt(kat) != 3)
        location += "&c=" + kat + "&si=" + $find(comboSearchId).get_selectedIndex() + "&w4=" + '8';
        
    document.location = location;
}
// ### Search Combo boxes functions START ### 




// Submit functions
function loginSubmit()
{
    if(!tryLoginActivated)
    {
        MPortal.User.TryLogin([$get('tbLogin').value,$get('tbPassword').value,$get('rememberme').checked],tryLoginCallback,tryLoginFailure);
        tryLoginActivated = true;
    }
}

function passwordRetrieve()
{
    MPortal.User.RetrievePasword([$get('email').value],passRetCallback,onFailure)
}

function sendRegistration()
{
    MPortal.User.RegisterPrivateUser([$get('regUsrName').value,$get('password').value,$get('passwordCnfrm').value,$get('emailPrvReg').value,$get('firstName').value,$get('surrName').value,$get('newsletterKnjizara').checked,$get('newsletterPoslovni').checked],registerUser,onFailure);
}

function sendRegistrationLeg()
{
    MPortal.User.RegisterLegalUser([document.getElementById('regUsrName').value,document.getElementById('password').value,document.getElementById('passwordCnfrm').value,document.getElementById('emailPrvReg').value,document.getElementById('company').value,document.getElementById('matBr').value,document.getElementById('newsletterKnjizara').checked,document.getElementById('newsletterPoslovni').checked],registerUser,onFailure);
}

/* friends */
var rJSON = null;


//Sys.Application.add_load(FriendsLoaded);

function friendsLoaded() 
{
    if(typeof(initUser) != "undefined")
        initUser();
}

function ApproveFriendCallback(e,userId)
{
    var userPanelDOM = $get('user' + userId);
    userPanelDOM.removeChild($get('approve' + userId));
    $get('friendsList').appendChild(userPanelDOM);
    $get('friendsList').appendChild($get('friendsClr'));
    MPortal.User.RefreshSession([],onSR,onFailure);
}



function RemoveFriendCallback(e,userId)
{
    var userPanelDOM = $get('user' + userId);
    userPanelDOM.parentNode.removeChild(userPanelDOM);
    MPortal.User.RefreshSession([],onSR,onFailure);
}

function onSR(e)
{
//blank
}


/*notify panel */

//Sys.Application.add_load(notifyPanelLoaded);
//Sys.Application.add_unload(notifyPanelUnLoaded);



function notifyPanelLoaded()
{
    queueTimer = new Sys.Timer();
    queueTimer.set_interval(4000);
    queueTimer.add_tick(checkMessagesQueue);
    queueTimer.set_enabled(true);
    
    //zadrzavanje panela vidljivim neko vrijeme izmedju fadeIn i fadeOut funkcija
    pause = new Sys.Timer();
    pause.set_interval(2000);
    pause.add_tick(fadeOut);
    
    cAlertDOM = notifyDlg.get_element();
    notifyDlg.hide();
    
    
    if(typeof(getNewFriendRequests) == "function" && notifyMessages)
        getNewFriendRequests();
    
    //event listeners (freezing message while mouseover)
    $addHandler(cAlertDOM,'mouseover',pauseDisable);
    $addHandler(cAlertDOM,'mouseout',animationPause);
}

function pauseDisable(e)
{
    pause.set_enabled(false);
}

function notifyPanelUnLoaded()
{
    if(!notifyMessages)
        return;
    $removeHandler(cAlertDOM,'mouseover',pauseDisable);
    $removeHandler(cAlertDOM,'mouseout',animationPause);
}

function showAlert(message)
{
    pause.set_enabled(false);
    if(fadeInPanel && fadeInPanel.get_percentComplete() < 100)
        fadeInPanel.stop();
    if(fadeOutPanel && fadeOutPanel.get_percentComplete() < 100)
        fadeOutPanel.stop();
        
    notifyDlg.hide();
    
    var alContent = document.createElement('a');
            alContent.id = 'aC';
            alContent.href = 'javascript:void(0);';

            alContent.className = 'messengerContent';
                var msgTit = document.createElement('h3');
                msgTit.innerHTML = message;
                alContent.appendChild(msgTit);
            alContent.Type = messageAlertType.exceptionMessage;
    
    alertsQueue.push(alContent);
    checkAlertsQueue();
}

//Stop regular messages Queue & show alert message(s)
function checkAlertsQueue()
{
    notifyDlg.hide();
    pause.set_enabled(false); 

    if(alertsQueue.size() > 0 )
    {   
        queueChecker = checkAlertsQueue;
        var message = alertsQueue.pop();
        showMessage(message);
    }
    else
    {
        queueChecker = checkMessagesQueue;
        queueChecker();
        return;
    }
    
}

function checkMessagesQueue()
{
    queueChecker = checkMessagesQueue;
    notifyDlg.hide();
    if(activeModalDialog)
    {
        queueTimer.set_enabled(false);
        queueTimer.set_interval(5000);
        queueTimer.set_enabled(true);
        pause.set_enabled(false);
        return;
    }
    
    pause.set_enabled(false); 
    
    if(queueTimer.get_interval() < 60000)
        {
        queueTimer.set_enabled(false);
        queueTimer.set_interval(60000);
        queueTimer.set_enabled(true);
        }
    queueTimer.set_enabled(false);

    if(messagesQueue.size() > 0 )
    {   
        var message = messagesQueue.pop();
        showMessage(message);
    }
    else
    queueTimer.set_enabled(true);

}

function closeNotify()
{
    pause.set_enabled(false);
    notifyDlg.hide();
    checkMessagesQueue();
}

function showMessage(elementToShow)
{
    //ocistimo message panel
    cAlertDOM.innerHTML = '';
    var mTitle = '';
    
    switch(elementToShow.Type)
    {
     case messageAlertType.privateMessage :
        mTitle = messageTitle.privateMessage;
        elementToShow.style.backgroundImage = messageIcon.privateMessageIcon;
        break;
     
     case messageAlertType.friendshipRequest :
        mTitle = messageTitle.friendshipRequest;
        elementToShow.style.backgroundImage = messageIcon.friendshipIcon;
        break;
        
     case messageAlertType.exceptionMessage :
        mTitle = messageTitle.exceptionMessage;
        elementToShow.style.backgroundImage = messageIcon.exceptionIcon;
        break;
    }

    cAlertDOM.innerHTML = "<div class=\"messengerHeader\"> <h4>" + mTitle + "</h4> <a href=\"javascript:closeNotify()\" title=\"Zatvori\">Zatvori</a> </div>";
    
    if(Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.Version == 6) 
    {
        setNotifyPanelPosIE6();
    }
    
    notifyDlg.show();
    if(elementToShow)
        {
        cAlertDOM.appendChild(elementToShow);
        }
    
    fadeIn();
}

function fadeOut()
{
    fadeOutPanel = new AjaxControlToolkit.Animation.FadeOutAnimation(cAlertDOM, 1, 35, 0, 1, false);
    fadeOutPanel.add_ended(queueChecker);
    fadeOutPanel.play();
}

function fadeIn()
{
    fadeInPanel = new AjaxControlToolkit.Animation.FadeInAnimation(cAlertDOM, 1, 35, 0, 1, false);
    fadeInPanel.add_ended(animationPause);
    fadeInPanel.play();
}

function animationPause()
{
   // pause.set_interval(2000);
    pause.set_enabled(false);
    pause.set_enabled(true);
}

var messageAlertType;
var messageIcon;
var messageTitle;



//crossBrowser opacity
function setOpacity(element,value)
{
    if(Sys.Browser.agent === Sys.Browser.Firefox)
    {
        element.style.opacity = value/100;
    }
    else{
        element.filters[0].opacity = value;
    }
}

/* PM modal */

//Sys.Application.add_load(modalLoaded);

var postId = null;
var messageTitle = null;
var isMessageOnAWay = false;

function modalLoaded()
{
    $addHandler(document.body,'keydown',keyPressHandler);
    
    var dlg = $find('PmDialog');
    
    if(dlg)
        {
            dlg.add_hiding(function(){submitFunction=null; activeModalDialog=null;});
            dlg.add_showing(function(){/*submitFunction=sendPM; */});
        }
    currentUser = new MPortal.User(currUserID);
}

function sendPM()
{
    if(isMessageOnAWay)
        return;
    recieversDOM = $get('recievers');
    messageTitle = $get('subject').value;
    for(r in recieversDOM.recievers)
        {
            var postLink = '';
            if(postId)
            {
                messageTitle = 'Prijava posta';
                postLink = "\r\n" + httpRoot + 'Forum/GoToPost.ashx?postId=' + postId;
            }
            currentUser.SendPMWithMesssageValidation([messageTitle,$get('privateMsg').value + postLink,recieversDOM.recievers[r]],sendPMCallback,onPmSendFailure);
        }
    isMessageOnAWay = true;
    submitFunction = null;
}

function onPmSendFailure(response)
{
    alert(response.Message);
    if(location.href.indexOf('User/PM.aspx') != -1)
        location.href = location.href;
    else
        $find('PmDialog').hide();
        
    isMessageOnAWay = false;
}

function getMods(responseJSON)
{
    CreateRecHeaders(responseJSON,false);
}


function readPmLink(msgId,args)
{
    modalReadPrepare(new MPortal.User(args[2]),$get(args[0]).innerHTML, $get(args[0]).parentNode.getElementsByTagName('input')[0].value,'readPM');
    PMessage = new MPortal.PM(msgId);
    if(args[3] != null)
        $get('Reply').style.display = 'none';
    PMessage.SetViewed([],setViewedCallBack,onFailure,args);
}

function setViewedCallBack(response,customArgs)
{
    $get(customArgs[0]).style.fontWeight = 'normal';
    $get(customArgs[1]).src = httpRoot + 'img/pmIcon.gif';
    
}

function modalReadPrepare(sender, pmTitle, pmText, messageType)
{
    //
    activeModalDialog='PmDialog';
    switch(messageType)
    {
        case 'readPM':
        var PMdialog = $find('PmDialog');
        $get(PMdialog.get_PopupControlID()).style.visibility = "";
        $get('sendPanel').style.display = 'none';
        $get('recievePanel').style.display = 'block';
        $get('titleMsg').innerHTML = pmTitle;
        $get('bodyMsg').innerHTML = pmText;
        $get('Ok').style.display = 'none';
        $get('Reply').style.display = 'block';
        $get('messageSent').style.display = 'none';
        
        sender._SetData(userFill,onFailure);
        //submitFunction = sendPM;
        PMdialog.show();
        break;
    }
}

function modalReplyPrepare(pmTitle, pmText)
{
    $get('subject').value = 'Re: ' + pmTitle;
    $get('subject').style.backgroundColor='#fff';
    $get('subject').disabled = false;
    $get('privateMsg').value = ''; //pmText;
    $get('privateMsg').style.backgroundColor='#fff';
    $get('privateMsg').disabled = false;
    $get('sendPanel').style.display = 'block';
    $get('recievePanel').style.display = 'none';
    $get('Ok').style.display = 'block';
    $get('Reply').style.display = 'none';
}

function modalPrepare(id , messageType)
{
    $get('messageSent').style.display = 'none';
    var textDOM = $get('privateMsg');
    textDOM.onfocus = function(){if(textDOM.value == 'Tekst poruke...' || textDOM.value == 'Razlog prijave upišite ovdje...') textDOM.value = '';};
    textDOM.onblur = function(){if(textDOM.value == '') textDOM.value = 'Tekst poruke...';};
    textDOM.disabled = false;
    textDOM.style.backgroundColor = '#fff';
    $get('Ok').style.display = 'block'; 
    $get('Reply').style.display = 'none';
         
    if(messageType == 'postNotification')
        {
        postId = id;
        new MPortal.Forum(forumID).GetModerators([],getMods,onFailure);
        $get('privateFoot').style.backgroundImage = 'url()';
        $get('unwanted').style.display = 'none';
        $get('subject').style.display = 'none';
        $get('Ok').innerHTML = 'pošalji';
        messageTitle = 'Prijava posta';
        }

    else if(messageType == 'privateMessage')
         {
         $get('Ok').innerHTML = 'pošalji';
         var user = new MPortal.User(id);
         user._SetData(userFill,onFailure);
         $get('privateFoot').style.backgroundImage = 'url(../img/modalPrivateMsgTitle.gif)';
         //
         $get('Ok').style.display = 'block';
         $get('Reply').style.display = 'none';
         //
         var textDOM = $get('privateMsg');
         
         var subjectDOM = $get('subject');
         subjectDOM.value = 'Naslov poruke...';
         subjectDOM.onfocus = function(){if(subjectDOM.value == 'Naslov poruke...') subjectDOM.value = '';};
         subjectDOM.onblur = function(){if(subjectDOM.value == '') subjectDOM.value = 'Naslov poruke...';};
         subjectDOM.style.display = 'block';
         subjectDOM.disabled = false;
         subjectDOM.style.backgroundColor = '#fff';
         }
}

function userFill(responseJSON)
{
    recs = new Array();
    recs.push(responseJSON);
    CreateRecHeaders(recs,true);
}

function CreateRecHeaders(mods , showHeader)
{
    recieversDOM = $get('recievers');
    recieversDOM.recievers = mods;
    recieversDOM.innerHTML = '';
    
    if(showHeader)
    {
        for(mod in mods)
        {
            var rootDiv = document.createElement("div");
            rootDiv.className = "privateHeader";
            rootDiv.user = mods[mod];
                
                var innerDiv = document.createElement("div");
                    
                    var avatarLnk = document.createElement("a");
                    avatarLnk.href = httpRoot + "User/UserDetail.aspx?UserID=" + mods[mod].Id;
                        
                        var avatarIMG = document.createElement("img");
                        avatarIMG.src = mods[mod].Avatar;
                        avatarIMG.alt = mods[mod].Login;
                        avatarIMG.className = 'avatarIMG';
                        avatarIMG.style.width = '55px';
                        avatarIMG.style.height = '55px';
                        avatarLnk.appendChild(avatarIMG);
                    
                    innerDiv.appendChild(avatarLnk);
                    
                    var paragraph = document.createElement("p");
                        var nickLnk = document.createElement("a");
                        nickLnk.href = httpRoot + "User/UserDetail.aspx?UserID=" + mods[mod].Id;
                        nickLnk.innerHTML = mods[mod].Login;
                        nickLnk.className = 'userName';
                        paragraph.appendChild(nickLnk);
                        
                        paragraph.innerHTML += ' | ';
                        
//                        var friendLnk = document.createElement("a");
//                        friendLnk.href = 'dodajuprijateljelink';
//                        friendLnk.innerHTML = 'dodaj u listu prijatelja';
//                        paragraph.appendChild(friendLnk);
//                        
//                        paragraph.innerHTML += ' | ';
                        
                        var profileLnk = document.createElement("a");
                        profileLnk.href = httpRoot + "User/UserDetail.aspx?UserID=" + mods[mod].Id;
                        profileLnk.innerHTML = 'profil';
                        paragraph.appendChild(profileLnk);
                        
                        //blog
                        if(mods[mod].BlogId != 0)
                        {
                            paragraph.innerHTML += ' | ';
                            var blogLnk = document.createElement("a");
                            blogLnk.href = httpRoot + 'Blog/LastPostRedirector.aspx?BlogID=' + mods[mod].BlogId;
                            blogLnk.innerHTML = 'blog';
                            paragraph.appendChild(blogLnk);
                        }
                        
                        paragraph.appendChild(document.createElement("br"));
                        paragraph.innerHTML += 'korisnik od: ' + mods[mod].DateCreated.format('dd.MM.yyyy.') + '<br />';
                        
                        
//                        var blogLnk = document.createElement("a");
//                        blogLnk.href = 'bloglink';
//                        blogLnk.innerHTML = 'blog';
//                        paragraph.appendChild(blogLnk);
                        
//                        paragraph.appendChild(document.createElement("br"));
//                        paragraph.innerHTML += 'korisnik od: ' + mods[mod].DateCreated.format('dd.MM.yyyy.'); + '<br />';
                    
                    innerDiv.appendChild(paragraph);
                    
                rootDiv.appendChild(innerDiv);
            
            recieversDOM.appendChild(rootDiv);
        }
        $get('privateMsg').value = 'Tekst poruke...';
    }
    else
        $get('privateMsg').value = 'Razlog prijave upišite ovdje...';
        
    var PMdialog = $find('PmDialog');
    $get(PMdialog.get_PopupControlID()).style.visibility = "";
    PMdialog.show();
}


/* send pm */

//Sys.Application.add_load(sendPMLoaded);

var rJSON = null;
var newMPTimer = null;
var alertedPMs = null;

function sendPMLoaded() 
{
    //hash tabela poruka poslanih na cAlert
    alertedPMs = new Hashtable();

    if(newPMNotification)
    {
        checkNewPMs();
        newMPTimer = new Sys.Timer();
        newMPTimer.set_interval(60000);
        newMPTimer.add_tick(checkNewPMs);   
        newMPTimer.set_enabled(true);
    }
}

function checkNewPMs()
{
    if(!httpRoot.startsWith("https:") && notifyMessages)
    {
        var currentUser = new MPortal.User(currUserID);
        currentUser.GetPMs(['New'],getNewPMsCallback, onNewPMFailure);
    }
}

function onNewPMFailure(err, args, userId)
{
    if(userId == anonymousID)
    {
        document.location = document.location;
        return;
    }
    onFailure(err,args,userId);
}



function getNewPMsCallback(messagesList)
{
    //DOM element s listom porukama koju saljemo u cAlert()

    if(newMPTimer.get_interval() > 59999)
        newMPTimer.set_interval(newMPTimer.get_interval() * 1.2);
    
    $get('newMsgs').innerHTML = messagesList.length;
    for(var mess in messagesList)
    {
        if(alertedPMs.get(messagesList[mess].PMID) == null)
        {
            var msgContent = document.createElement('a');
            msgContent.id = 'mC' + messagesList[mess].PMID;
            msgContent.href = "javascript:prepPmModal($get('"+msgContent.id+"'));";
            msgContent.sender = messagesList[mess].Sender;
            msgContent.mT = messagesList[mess].Title;
            msgContent.mM = messagesList[mess].Message;
            msgContent.mTyp = 'readPM';
            msgContent.PM = messagesList[mess];

            msgContent.className = 'messengerContent';
                var msgTit = document.createElement('h3');
                msgTit.innerHTML = messagesList[mess].Title.length > 25 ? messagesList[mess].Title.substring(0,23) + '...' : messagesList[mess].Title;
                msgContent.appendChild(msgTit);
                
                var msgSender = document.createElement('p');
                msgSender.className = 'author';
                msgSender.innerHTML = messagesList[mess].Sender.Login;
                msgContent.appendChild(msgSender);
                
                var msgDate = document.createElement('p');
                msgDate.className = 'date';
                msgDate.innerHTML = messagesList[mess].DateSent.localeFormat("MM/dd/yyyy") + ' | ' + messagesList[mess].DateSent.localeFormat("HH:mm");
                msgContent.appendChild(msgDate);
                
            alertedPMs.put(messagesList[mess].PMID , true);
            msgContent.Type = messageAlertType.privateMessage;
            messagesQueue.push(msgContent);
            msgContent = null;
        }
    }
}

function setViewedCB(res)
{

}

function prepPmModal(el)
{
    el.PM.SetViewed([],setViewedCB,onFailure);
    var msgSpan = $get('newMsgs');
    var msgCount = parseInt(msgSpan.innerHTML);
    msgSpan.innerHTML = msgCount - 1;
    modalReadPrepare(el.sender, el.mT, el.mM, el.mTyp);
    el.href = "javascript:void(0);";
}

function sendPMCallback(responseJSON)
{
    //leave it empty
    var subjectDOM = $get('subject');
    var textDOM = $get('privateMsg');
    var okButtonDOM = $get('Ok');
    
    subjectDOM.style.backgroundColor = '#e2dcf2';
    subjectDOM.disabled = true;
    textDOM.style.backgroundColor = '#e2dcf2';
    textDOM.disabled = true;
    okButtonDOM.style.display = 'none';
    $get('messageSent').style.display = 'block';
    isMessageOnAWay = false;
}

function sendFriendsRequestCallback(e, targetCtl)
{
    if (e > -1) {
        showAlert("Zahtjev za prijateljstvo je odbijen.");
    }
    else {
        var ctl = targetCtl != null ? targetCtl : friends;
        $get(ctl).innerHTML = "Poslan je zahtjev za prijateljstvom";
        $get(ctl).onclick = null;
        $get(ctl).href = 'javascript:void(0);';
        $get(ctl).style.textDecoration = 'none';
        $get(ctl).style.color = '#686767';
        $get(ctl).style.cursor = 'default';
        MPortal.User.RefreshSession([], onSR, onFailure);
    }
}

function sendFriendsRequestCallbackPosts(e,additionalParams)
{
    if (e > -1) {
        showAlert("Zahtjev za prijateljstvo je odbijen.");
    }
    else {
        RefreshAllLinks(additionalParams[1]);
        MPortal.User.RefreshSession([], onSR, onFailure)
    }
}

function sendFriendRequestFailure(err) {
    showAlert(err.Message);
}

function addUserToIgnoreListCallBack(e, additionalParams) {

    var ignoreUserCtl = $get(ignoreUser);   // span
    ignoreUserCtl.innerHTML = "korisnik je na <a href='" + httpRoot + "User/Userfriends.aspx' title='Pregledaj listu ignoriranih korisnika' target='_blank'>listi ignoriranih korisnika</a>";

    $get(prMsgControl).style.display = 'none';
    $get('friendReqSeparator').style.display = 'none';
    $get(friends).style.display = 'none';
    $get('ignoreSeparator').style.display = 'none';
    
    
    MPortal.User.RefreshSession([], onSR, onFailure); 
}

function RefreshAllLinks(val)
{
    var arr = document.getElementsByTagName('cite');
    
    var link;
    for(var i = 0 ; i < arr.length ; i++)
    {
        link = arr[i].parentNode;
        if(arr[i].innerHTML.trim() == val.toString()) 
        {
            link.style.color = '#686767';
            link.style.textDecoration = 'none';
            link.style.cursor = 'default';
            link.href = 'javascript:void(0);';
            link.attributes["onclick"].nodeValue = 'javascript:void(0);';
            link.removeChild(link.firstChild);
            link.appendChild(document.createTextNode("Poslan je zahtjev za prijateljstvom"));
        }
    }
}

function onSR(e)
{
//blank
}

function onFailure(e)
{
   //showAlert(e.Message);
}






Sys.Application.add_load(userCallsLoaded);
Sys.Application.add_unload(userCallsUnLoaded);


if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


