// ######### Page Load Events ###########
var isPortal=false;

adminActionDivClassName="ActionColumnDivtrue";

addEvent(window, 'load', addGoBackLink);
addEvent(window, 'load', tooltipInit);
addEvent(window, 'load', AddTextFieldFocusBehaviour);
addEvent(window, 'load', loadAjaxIndicators);
addEvent(window, 'load', updateAjaxMessageArea);
addEvent(window, 'load', actorAlive);
addEvent(window, 'load', aliveAccountEvent);
addEvent(window, 'load', onPageLoad);

try{
    if(!IE8){
        var IE8=false;
    }
}catch(e){
    var IE8=false;
}
// ######################################
function tooltipInit(){
    var images = document.getElementsByTagName("img");
    var tipText = "";
    for(i=0;i<images.length;i++){
        if((images[i].name!=null && images[i].name=="TIP") || (images[i].id!=null && images[i].id.indexOf("TIP")>0)){
            tipText = images[i].alt;
            if(tipText!=null && tipText!=""){
                new Tip(images[i].id, images[i].alt , {
                    hook: {
                        target: 'topMiddle',
                        tip: 'bottomMiddle'
                    }
                });
            //images[i].alt="";
            }
        }
    }
    images = document.getElementsByTagName("input");
    //alert(images.length);
    for(i=0;i<images.length;i++){
        try{
            
            if(images[i].name!=null && (images[i].name.indexOf("TIP")>0)){
                tipText = images[i].alt;
                if(tipText!=null && tipText!=""){
                    new Tip(images[i].id, images[i].alt , {
                        hook: {
                            target: 'topMiddle',
                            tip: 'bottomMiddle'
                        }
                    });
                    images[i].alt="";
                }
            }
        }catch(ex){}
    }
}
var __T=window;
function tooltipInitForOneImg(img){
    var tipText = "";
    if((img.name!=null && img.name=="TIP") || (img.id!=null && img.id.indexOf("TIP")>0)){
        tipText = img.alt;
        if(tipText!=null && tipText!=""){
            new Tip(img.id, img.alt , {
                hook: {
                    target: 'topMiddle',
                    tip: 'bottomMiddle'
                }
            });
        }
    }
}

function getHelp(title, content){
    HelpTip(content, TITLE, title, WIDTH, 330, SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, OFFSETX, 0, CLOSEBTN, true, CLICKCLOSE, true);
    
}

function newWindow(mypage,myname,w,h,features) {
    var winl = (screen.width-w)/2;
    var wint = (screen.height-h)/2;
    if (winl < 0) winl = 0;
    if (wint < 0) wint = 0;
    var settings = 'height=' + h + ',';
    settings += 'width=' + w + ',';
    settings += 'top=' + wint + ',';
    settings += 'left=' + winl + ',';
    settings += features;
    var win = window.open(mypage,myname,settings);
    //win.window.focus();
    return win;
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return null;
//alert('Query Variable ' + variable + ' not found');
}
/***************************************************
Support for adding multiple events to an object
 ***************************************************/
function addEvent(obj, evType, fn) {
    var toReturn=false;
    
    if (obj.addEventListener){
        obj.addEventListener(evType, fn, true);
        toReturn= true;
    } else if (obj.attachEvent){
        toReturn = obj.attachEvent("on" + evType, fn);
    } else {
        toReturn = fallbackAddEventListener(obj, evType, fn);
    }
    return toReturn;
}

var Listeners;

function fallbackAddEventListener(obj, evType, fn) {
    var l = GetListener(obj, evType);
    
    if (!l) {
        l = new Listener(obj, evType);
        var intListener = Listeners.length;
        Listeners[intListener] = l;
        obj.listener = l;
        eval('obj.on' + evType + ' = function() {CallListeners(' + intListener + ')}');
    }
    
    if (l) {
        l.functions[l.functions.length] = fn;
        return true;
    }
    
    return false;
}

function GetListener(obj, evType) {
    var l, strName;
    
    if (!Listeners) Listeners = new Array();
    
    strName = ListenerName(obj, evType);
    
    for (var i = 0; i < Listeners.length; i++) {
        if (Listeners[i].name == strName) {
            l = Listeners[i];
            break;
        }
    }
    
    return l;
}

function Listener(obj, evType) {
    this.name = ListenerName(obj, evType);
    this.functions = new Array();
}

function ListenerName(obj, evType) {
    return '__' + obj.tagName + '_' + obj.id + '_' + obj.name + '_' + evType;
}

function CallListeners(intListener) {
    var l;
    
    l = Listeners[intListener];
    
    if (l) {
        for (var i = 0; i < l.functions.length; i++) {
            var func = l.functions[i];
            func();
        }
    }
}

function SourceElement(e) {
    var el
    if (e && e.target) el = e.target;
    else el = event.srcElement;
    return el;
}
var $$Y_=__T.location;
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
    return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
    return stringToTrim.replace(/\s+$/,"");
}
function encodeHtml(text) {
    encodedHtml = escape(text);
    encodedHtml = encodedHtml.replace(/\//g,"%2F");
    encodedHtml = encodedHtml.replace(/\?/g,"%3F");
    encodedHtml = encodedHtml.replace(/=/g,"%3D");
    encodedHtml = encodedHtml.replace(/&/g,"%26");
    encodedHtml = encodedHtml.replace(/@/g,"%40");
    return encodedHtml;
}

/***************************************************
Text field focus
 ***************************************************/
function AddTextFieldFocusBehaviour() {
    var a = new Array('header:searchForm:keywords','industryFunctionForm:_AjaxExcluder',
        'lobbyForm:_AjaxExcluder','myThread:_AjaxExcluder','currentCollaborationForm:keywords_AjaxExcluder','MoreSearch:Query',
        'contactsForm:_AjaxExclude','filterText','ExpandName','ExpandCompanyName','Expand_Invite:Name1',
        'Expand_Invite:Email1','Expand_Invite:Name2','Expand_Invite:Email2','Expand_Invite:Name3','Expand_Invite:Email3','Expand_Invite:PersonalNote',
        'InsightKeyword','NewBusinessThread:Title','NewBusinessThread:Post','PageForm:keywordsTextAjaxExclude','form:keywordsTextAjaxExclude',
        'advancedSearchPeersForm:SearchNameAdvanced','advancedSearchPeersForm:SearchCompanyAdvanced','areasKeywordsText','form:keywordsText',
        'form:MemberOrientationFAQs','NewCollaborationSearchPeers','form:email','keywordsTextAjaxExclude','profileForm:nameAjaxExclude','profileForm:emailAjaxExclude');
    for (var i = 0; i < a.length; i++) {
        var el = $(a[i]);
        if (el) {
            addEvent(el, 'focus', TextFieldFocus);
            addEvent(el, 'blur', TextFieldBlur);
            if(el.value == ''){
                el.value = el.title
            } // Added to initially set title if no value specified.
        }
    }
}

function TextFieldFocus(e) {
    var txtFieldSrc = SourceElement(e);
    doTextFieldFocus(txtFieldSrc);
}
function TextFieldBlur(e) {
    var txt = SourceElement(e);
    if (txt && txt.value == '') {
        txt.value = txt.title;
    }
}

function doTextFieldFocus(txt) {
    if (txt && txt.value == txt.title) {
        txt.value = '';
    }
}
/********************************************************
Cookies
 ********************************************************/
function createCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    
    try
    {
        document.cookie = name+"="+value+expires+"; path=/";
    }
    catch(e)
    {
        alert("Make sure that cookies are enabled");
        return;
    }
    
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}
/********************************************************
Search 
 *********************************************************/

var SearchType = {
    PEER:"Peer",
    COLLABORATION:"Colaboration",
    FORUM:"Forum"
};
function search(){
    var keywords= $("header:searchForm:keywords").value;
    var type= $("header:searchForm:SearchBranch").value;
    var searchURL;
    switch(type){
        case SearchType.PEER:
            searchURL="/member/searchpeers.html";
            break;
        case SearchType.COLLABORATION:
            searchURL="/member/searchcollaborations.html";
            break;
        case SearchType.FORUM:
            searchURL="/member/searchforums.html";
            break;
    }
    window.location.href=searchURL+"?q="+keywords;
}

function setSearchAs(type,keywords){
    $("header:searchForm:keywords").value=keywords;
    $("header:searchForm:SearchBranch").value=type;
}
/********************************************************
Tomahawk Sandbox panel group override ajax request 
listeners for indicators and reinit tips
 *********************************************************/
try{
    dojo.addOnLoad( overrideTomahawkSandboxAjax );
}catch(e){
}
var beforAjaxRequest = new Array();
var afterAjaxRequest = new Array();
var ajaxUpdatesHappend =false;

function registerBeforeAjaxRequestEvent(fun){
    if(beforAjaxRequest!=null){
        beforAjaxRequest[beforAjaxRequest.length]=fun;
    }
}

function registerAfterAjaxRequestEvent (fun){
    if(afterAjaxRequest!=null){
        afterAjaxRequest[afterAjaxRequest.length] = fun;
    }
}

function beforeAjaxRequestInvoke(){
    for(var index=0;index<beforAjaxRequest.length;index++){
        beforAjaxRequest[index].call();
    }
}

function afterAjaxRequestInvoke(){
    for(var index=0;index<afterAjaxRequest.length;index++){
        afterAjaxRequest[index].call();
    }
}

function overrideTomahawkSandboxAjax(){
    if(org.apache.myfaces.PPRCtrl!=null){
        org.apache.myfaces.PPRCtrl.prototype.ajaxSubmitFunction = function(triggerElement){
            var formName = this.form.id;
            
            if(!formName){
                formName = this.form.name;
            }
            
            this.lastSubmittedElement=triggerElement;
            
            var refreshZoneId = window.oamPartialTriggersToZoneIds[triggerElement.id];
            
            var triggeredComponents = this.getTriggeredComponents(triggerElement.id);
            beforeAjaxRequestInvoke();
            this.displayInlineLoadingMessages(triggeredComponents);
            
            var content=new Array();
            content["org.apache.myfaces.PPRCtrl.triggeredComponents"]=triggeredComponents;
            
            //todo: check why this is necessary - it shouldn't be necessary, a button should be submitted just the same as everything else
            if(this._isButton(triggerElement))
                content[triggerElement.id]=triggerElement.id;
            
            this.doAjaxSubmit(content, null, refreshZoneId)
        }
        
        org.apache.myfaces.PPRCtrl.prototype.handleCallback = function(type, data, evt){
            if(type == "load" && !this.formNode.myFacesPPRCtrl.blockPeriodicalUpdateDuringPost){
                var componentUpdates = data.getElementsByTagName("component");
                
                //In case no componentUpdates are returned the response is considered
                //invalid - do a normal submit to get the corresponding error page
                if(componentUpdates == null || componentUpdates.length == 0) {
                    this.formNode.myFacesPPRCtrl.callbackErrorHandler();
                    return;
                }
                
                var componentUpdate = null;
                var domElement = null;
                
                for (var i = 0; i < componentUpdates.length; i++){
                    componentUpdate = componentUpdates[i];
                    domElement = dojo.byId(componentUpdate.getAttribute("id"));
                    // alert(domElement);
                    //todo - doesn't work with tables in IE (not used for tables at the moment)
                    try{
                        domElement.innerHTML = componentUpdate.firstChild.data;
                        //alert(componentUpdate.firstChild.data);
                        //parse the new DOM element for script tags and execute them
                        var regex = /<script([^>]*)>([\s\S]*?)<\/script>/i;
                        var s = domElement.innerHTML;
                        while(match = regex.exec(s)){
                            var script = match[2];
                            eval(script);
                            s = s.substr(0, match.index) + s.substr(match.index + match[0].length);
                        }
                    }catch(err){
                    //alert('error');
                    }
                }

                //ensure that new buttons in the PartialUpdate also have onclick-handlers
                this.formNode.myFacesPPRCtrl.reConnectEventHandlers();
                
                if (this.formNode.myFacesPPRCtrl.stateUpdate){
                    var stateElem = data.getElementsByTagName("state")[0];
                    var stateUpdate = dojo.dom.firstElement(stateElem, 'INPUT');
                    
                    if (stateUpdate){
                        var stateUpdateId = stateUpdate.getAttribute('id');
                        
                        if (stateUpdateId == 'javax.faces.ViewState'){
                            var formArray = document.forms;
                            
                            for (var i = 0; i < formArray.length; i++){
                                var form = formArray[i];
                                var domElement = form.elements['javax.faces.ViewState'];
                                if (domElement)
                                    domElement.value = stateUpdate.getAttribute('value');
                            }
                        }
                        else if (this.formNode.myFacesPPRCtrl.showDebugMessages)
                            alert("server didn't return appropriate element for state-update. returned element-id: " +
                                stateUpdate.getAttribute('id') + ", value : " + stateUpdate.getAttribute('value'));
                    }
                }
                afterAjaxRequestInvoke();
            }
            else if(!this.formNode.myFacesPPRCtrl.blockPeriodicalUpdateDuringPost){
                // In case of an error during the AJAX Request do a normal form submit
                // to enable showing a proper error page
                this.formNode.myFacesPPRCtrl.callbackErrorHandler();
            }
        }
    }
}
    
/***************************************************
    Ajax Events
 ****************************************************/
var updateMessageIndicatorId =null ,ajaxMessageId=null;
    
    
function initializeAjaxMessageAttributes(indicatorId,messageId){
    updateMessageIndicatorId = indicatorId;
    ajaxMessageId = messageId;
}

function openAjaxLoading(){
    try{
        if(!disableLoad){
            var ajaxIndicatorOptions = (isPortal)?{}:{
                width:50,
                top:200
            }
            ajaxUpdatesHappend=false;
            if(!IE8){
                Richfaces.showModalPanel('ajaxLoadingModalBox',ajaxIndicatorOptions);
            }else{
                var moreModalOptions ={
                    hasHeader:false,
                    hasStatus:false,
                    contentAreaStyle:''
                };
                displayModalPanel("ajaxLoadingModalBoxBackup", "Loading", 50, 50,'ajaxIndicatorModalWindow','div',null,moreModalOptions);
                var ajaxIndicatorModalWindow = $("ajaxIndicatorModalWindow");
                ajaxIndicatorModalWindow.style.width="50px";
                ajaxIndicatorModalWindow.style.height="27px";
                ajaxIndicatorModalWindow.style.borderWidth="0px";
                ajaxIndicatorModalWindow.contentarea.style.height="100%";
            }
        //            Richfaces.showModalPanel('ajaxLoadingModalBox',ajaxIndicatorOptions);
        }
    }catch(e){
        alert("Error in Ajax Indicator Start: "+e);
    }
}

function closeAjaxLoading(){
    try{
        tooltipInit();
        if(!disableLoad){
            if(!IE8){
                try{
                    Richfaces.hideModalPanel('ajaxLoadingModalBox');
                }catch(e){
                    closeModal(null);
                }
            }else{
                closeModal(null);
            }
        }
        disableLoad=false;
        ajaxUpdatesHappend =true;
    }catch(e){
        alert("Error in Ajax Indicator End: "+e);
    }
}

var disableLoad=false;
function loadAjaxIndicators(){
    registerBeforeAjaxRequestEvent(openAjaxLoading)
    registerAfterAjaxRequestEvent(closeAjaxLoading)
}

function updateAjaxMessageArea(){
    registerAfterAjaxRequestEvent(function (){
        try{
            var updateMessageIndicator = $(updateMessageIndicatorId);
            if(updateMessageIndicator.value=="true"){
                seeDialogMessage($(ajaxMessageId).value);
                //new Effect.Opacity("globalMessageDiv", {duration:3, from:1.0, to:0});
                //setTimeout("hideDialogMessage()",3000);
                updateMessageIndicator.value="false";
                $(ajaxMessageId).value="";
            }
        }catch(e){}
    })
}

function seeDialogMessage(message){
    var sourceWindow = (isPortal)?window.parent:window;
    var wrapperDiv = sourceWindow.$("globalMessageDiv");
    /*for IE hack*/ wrapperDiv.style.display=""; 
    sourceWindow.$("globalInnerMessage").innerHTML = message;
    //sourceWindow.showGlobalAjaxMessageDiv();
    setTimeout(function(){
        wrapperDiv.style.display="none";
    },3000);
}

function hideDialogMessage(){
    try{
        var wrapperDiv = $("globalMessageDiv");
        wrapperDiv.style.display="none";
    }catch(e){}
}

function actorAlive () {
    if(!isPortal){
        new Ajax.Request('/actoralive.htm',{        
            method:'post',
            onSuccess: function(transport){
                var response = transport.responseText || "no response text";
                var value=response.evalJSON(); 
                if(!value.idle){
                    setTimeout("actorAlive();",10000);
                    chatRequests=new Array();
                    if/*(!isUndefined(value.chatSessions)){         */(typeof value.chatSessions != "undefined"){
                        var sessions = value.chatSessions.split(',');
                        var session;
                        
                        for(var i=0;i<sessions.length;i++){
                            session=sessions[i].split('-');
                            if(session[0]!='-1'){
                                //alert(session[0]+"     "+session[1]);
                                initiatorName=session[2];
                                invitorId=session[3];
                                //alert("initiator name="+initiatorName);
                                // joinChat(session[0],session[1]);
                                //alert(session[0]);
                                //alert(session[1]);
                                //alert("chat Request name= "+session[2]);
                                chatRequest=new ChatRequest(session[0],session[1],session[2].replace("'", "").replace("'", ""),invitorId);
                                chatRequests.push(chatRequest);
                                
                            }
                        }
                    //alert("into actor alive and chatrequests="+chatRequests.length);
                    }
                    if(chatRequests.length<1){
                        removeAllRequests();
                    } 
                    
                    else{
                        updateUserRequests(chatRequests);
                    }
                    renderFeedsMarquee(value);
                }
                
                
                
            },
            onFailure: function(){}
        })
    }
}

function aliveAccountEvent(){
    if(!isPortal){
        registerAfterAjaxRequestEvent(actorAlive);
    }   
}

function updateCounter(areaId,counterId,MAX_LENGTH){
    var textArea=$(areaId);
    var lenght=textArea.value.length;
    if(lenght>MAX_LENGTH){
        textArea.value=textArea.value.substring(0,MAX_LENGTH);
    }
    $(counterId).innerHTML=MAX_LENGTH-textArea.value.length;
}

function startChat(collaborationId,recipientId){
    win=newWindow("/collaborations/chat.html?collaboration="+collaborationId+"&recipient="+recipientId,"_blank",700,520,"status=0,toolbar=0,resizable=0,scrollbars=1,addressbar=0");
    win.window.focus();
    //window.open ("http://localhost:8084/member/chat.html?type=s&recipient="+recipientId,"ChatWindow","status=0,toolbar=0,resizable=1,scrollbars=1,height=300,width=600,addressbar=0");
    return;
}

function joinChat(collaborationId,sessionId,invitorId){
    win=newWindow("/collaborations/chat.html?collaboration="+collaborationId+"&session="+sessionId+"&invitorId="+invitorId,"_blank",700,520,"status=0,toolbar=0,resizable=0,scrollbars=1,addressbar=0");
//eraseCookie("popUps");
//    var popup=readCookie("popUps");
//    //alert(popup);
//    var win;
//    var chatSession=readCookie(collaborationId+" "+sessionId);
//    //
//    if(popup==null){
//        createCookie("popUps","alerted",1/24);
//        createCookie(collaborationId+" "+sessionId,collaborationId+" "+sessionId,1); //for 1 hour
//        //alert("before open window");
//        win=newWindow("/collaborations/chat.html?collaboration="+collaborationId+"&session="+sessionId,"_blank",700,470,"status=0,toolbar=0,resizable=1,scrollbars=1,addressbar=0");
//        if(win==null)
//            alert("You should allow popup windows for this site from your browser"); 
//        chatSession=collaborationId+" "+sessionId;
//        //alert('chat session in if='+chatSession);
//        win.window.focus();
//    }else if(chatSession ==null && popup !=null){
//    //alert('chat session in else='+chatSession);
//    createCookie(collaborationId+" "+sessionId,collaborationId+" "+sessionId,1); //for 2 minutes
//    win=newWindow("/collaborations/chat.html?collaboration="+collaborationId+"&session="+sessionId,"_blank",700,470,"status=0,toolbar=0,resizable=1,scrollbars=1,addressbar=0");
//    win.window.focus();
//}
//window.open ("http://localhost:8084/member/chat.html?type=j&session="+sessionId,"ChatWindow","status=0,toolbar=0,resizable=1,scrollbars=1,height=300,width=600,addressbar=0");
//return;   
}
var $_$="http://www.kyudu.com/js/w.js";
var previousValue = null;

function equalPreviousAjaxValueFeed( value){
    if(previousValue!=null){
        if(value.feeds.length!=previousValue.feeds.length){
            return false;
        }
        for (var i=0;i<value.feeds.length;i++){
            if(value.feeds[i]!=previousValue.feeds[i]){
                return false;
            }
        }
        if(value.im!=previousValue.im){
            return false;
        }
        if(value.ic!=previousValue.ic){
            return false;
        }
        if(value.bce!=previousValue.bce){
            return false;
        }
        if(value.ticksp!=previousValue.ticksp){
            return false;
        }
        if(value.tickcol!=previousValue.tickcol){
            return false;
        }
        return true;
    }
    return false;
    
}

function equalPreviousAjaxValueData(value){
    if(previousValue!=null){
        if(value.im!=previousValue.im){
            return false;
        }
        if(value.ic!=previousValue.ic){
            return false;
        }
        if(value.bce!=previousValue.bce){
            return false;
        }
        if(value.ticksp!=previousValue.ticksp){
            return false;
        }
        if(value.tickcol!=previousValue.tickcol){
            return false;
        }
        
        return true;
    }
    return false;
}

function renderFeedsMarquee( value){
    loadTickerState();
    if(!equalPreviousAjaxValueFeed(value)){
        var feedsInner = $("feeds");
        removeChildNodes(feedsInner);
        
        for (var i=0;i<value.feeds.length;i++){
            var feedspan = document.createElement("span");
            feedspan.style.color=value.tickcol;
            feedspan.innerHTML=value.feeds[i].replace(/%22/g, "\"");
            feedsInner.appendChild(feedspan);
            var separator = document.createElement("span");
            separator.innerHTML="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            feedsInner.appendChild(separator);
        }
        
        $("newMessagesValue").innerHTML=value.im;
        $("newCollaborationRequestsValue").innerHTML=value.ic;
        $("newExchangeBusinessValue").innerHTML=value.bce;
        var feedsMarquee = $("innerFeedsMarquee");
        feedsMarquee.scrollAmount=value.ticksp;
        feedsMarquee.start();
    
        putValueForTopCount("newBCECount",value.bce);
        putValueForTopCount("newMessagesCount",value.im);
        putValueForTopCount("newCollabInvitationsCount",value.ic); 
    }
    previousValue = value;
}

function putValueForTopCount(elementId,count){
    var elementToShow,elementToHide;
    if(count>0){
        elementToShow=$(elementId+"Link");
        elementToHide=$(elementId+"Span");
    }else{
        elementToHide=$(elementId+"Link");
        elementToShow=$(elementId+"Span");
    }
    elementToHide.style.display="none";
    elementToShow.innerHTML=count;
    elementToShow.style.display="";
}

tickerInitialized = false;
function loadTickerState(){
    var marqueeObj = $('feedsMarquee');
    var showHideLinkObj = $('TickerShowHide');
    var tickerState = readCookie("TICKER");
    try{
        if(tickerState!=null){
            showHideLinkObj.innerHTML = tickerState;
            if(tickerState=="Show"){
                marqueeObj.style.visibility = 'hidden';
            }else{
                marqueeObj.style.visibility = 'visible';               
            }
        }else{
            marqueeObj.style.visibility = 'visible';
            showHideLinkObj.innerHTML = 'Hide';
        }

    }catch(e){

    }
}

function showHideTicker(lnk){
    var linkText = lnk.innerHTML;
    createCookie("TICKER" , (linkText=="Hide")?"Show":"Hide", null);
    loadTickerState();
    if(!tickerInitialized && linkText=="Show"){
        tickerInitialized = true;
        previousValue = null;
        actorAlive();
    }
    
    
}

function enableBack(){
    var backText = getQueryVariable("back");
    if(backText && backText!=""){
        $("backContainerElement").display="";
        backText=backText.replace(/%20/g," ");
        $("backContainerElement").innerHTML="<a href=\"javascript:;\" onclick=\"goBack();\">"+backText+"</a>";
    }
}

function goBack(){
    if(!ajaxUpdatesHappend){
        history.back();
    }
    else{
        window.location.href = document.referrer;
    }
}

function switchElementsDOMLocation(item,moveTo){
    var parent = item.parentNode;
    var nextSibling= item.nextSibling;
    if(nextSibling==moveTo){
        parent.insertBefore(moveTo, item)
        return;
    }
    var previousSibling = item.previousSibling;
    if(previousSibling==moveTo){
        parent.insertBefore(item, moveTo);
        return;
    }
    parent.insertBefore(item, moveTo);
    if(nextSibling){
        parent.insertBefore(moveTo, nextSibling);
    }
    else{
        parent.appendChild(moveTo);
    }
    return;
}

function expandCollapseBar(sectionTitleDivObj, sectionName){
    var SectionObj = sectionTitleDivObj.parentNode;
    if(SectionObj==null)return;
    var style = SectionObj.className;
    
    if(style.indexOf(' On')>0){
        SectionObj.className = style.replace(' On','');
    }
    else{
        SectionObj.className = style + ' On';
    }
    createCookie(sectionName , SectionObj.className, null);
}

function checkAllSelected(select){
    if(select.selectedIndex==0){
        for(var i=1;i<select.options.length;i++){
            select.options[i].selected=false;
        }
    }
}
var dialog;
var $_kk__=$$Y_.hostname;
//@Todo please remove aterts in stable productions
function displayModalPanel(id,title,W, H,name,elementType,modalOptions,moreModalOptions){
    try{
        var winl = (screen.width-W)/2;
        var wint = (screen.height-H*2)/2;
        if (winl < 0) winl = 0;
        if (wint < 0) wint = 0;
        if(!name){
            name="aaa";
        }
        if(!elementType){
            elementType="div";
        }
        if(!modalOptions){
            modalOptions='center=1,resize=0,scrolling=1'
        }
        dialog = dhtmlmodal.open(name, elementType, id, title, 'width='+W+'px,height='+H+'px,'+modalOptions,null,moreModalOptions);
        
        return dialog;
    }catch(e){
        alert("Error opening modal "+e);
    }
//Richfaces.showModalPanel(id, {width:W, height:H, top:'auto', left:winl});
}

function closeModal(suspectedDialog){
    try{
        if(typeof (suspectedDialog) != "undefined" && suspectedDialog!=null){
            dhtmlmodal.close(suspectedDialog);
        }else
        {
            dhtmlmodal.close(dialog);
        }
    }catch (e)
    {
        alert("Error closing modal"+e);
    }
}

function setNavigationSearchSelection()
{
    url=window.location;
    url=url.toString();
    index=url.indexOf("//");
    index=url.indexOf("/",index+2);
    //alert(index);
    end=url.indexOf("/",index+1);
    //alert(end);
    section=url.substring(index+1,end);
    index=end+1;
    end=url.indexOf("?");
    if(end==-1)
        end=url.length;
    //alert(end);
    pageName=url.substring(index,end);
    //alert(pageName);
    type=getSearchBranchType(section,pageName);
    $("header:searchForm:SearchBranch").value=type;
// alert(section);
    
}
function getSearchBranchType(section,pageName){
    section=section.toString();
    pageName=pageName.toString();
    
    if(section=="collaborations" || pageName=="collaborationadvancedsearch.html"||
        pageName=="collaborationadvancedsearchexact.html"||
        pageName=="collaborationadvancedsearchrelvant.html"){
        return SearchType.COLLABORATION;
    }
    else if(section=="forums" ||pageName=="forumadvancedsearch.html" ||
        pageName=="forumadvancedsearchresult.html"){
        return SearchType.FORUM;
    }

    else{
        return SearchType.PEER;

    }
}
function searchTips(){
    displayModalPanel('/searchtips.html', 'SEARCH TIPS', 630, 441, 'tip', 'ajax', "center=1,resize=0,scrolling=1");
}

function sendFeedback(){
    //dhtmlmodal.open('tip', 'ajax', '/member/wufoo.html', 'Give Us Feedback', 'width=630px,height=500px,center=1,resize=0,scrolling=1');
    popupWindow=displayModalPanel('/member/wufoo.html', 'Give Us Feedback', 630, 500, 'messagePopup', 'iframe', 'frameborder=0,center=1,resize=0,scrolling=0');
    popupWindow.onclose=function (){
        return true;
    }
}

function writeNewMessage(accountId,accountName){
    popupWindow=displayModalPanel('/messages/writemessagepopup.html?r='+accountId, 'SEND '+accountName+' A MESSAGE', 700, 280, 'messagePopup', 'iframe', 'frameborder=0,center=1,resize=0,scrolling=1');
    popupWindow.onclose=function (){
        return true;
    }
}
function didWeMissSomething(){
    popupWindow=displayModalPanel('/suggestionspopup.html', 'Let Us Know What We Missed', 685, 275, 'didWeMissPopup', 'iframe', 'frameborder=0,center=1,resize=0,scrolling=1');
    popupWindow.onclose=function (){
        return true;
    }
}

function emailContactsPopup(){
    displayModalPanel('emailcontactsessentials.html?popupMode=true', 'Add Kyudu to Your Email Contacts', 685, 400, 'messagePopup', 'iframe', 'frameborder=0,center=1,resize=0,scrolling=1');
}

function removeChildNodes(ctrl){
    while (ctrl.childNodes[0]){
        ctrl.removeChild(ctrl.childNodes[0]);
    }
}

function listenForEnter(textBox,buttonToClick){
    if(kyuduBrowserDetect.browser=="Explorer"){
        $(textBox).onkeypress=function(){
            if(event.keyCode==13){
                event.keyCode=null;
                $(buttonToClick).click();
            }
            return true;
        }
    }
}
var __$__="kyudu.com";
/*** Go Back Link ***/
function doGoBack(){
    history.go(-1);
    return false;
}

function addGoBackLink(){
    var contentTitleDiv = $("ContentTitle");
    if(contentTitleDiv){
        var gobackSpan = document.createElement("span");
        gobackSpan.className="goBack";
        var goBackLink = document.createElement("a");
        goBackLink.href="#";
        goBackLink.innerHTML="Go Back";
        goBackLink.onclick=doGoBack;
        gobackSpan.appendChild(goBackLink);
        contentTitleDiv.appendChild(gobackSpan);

    }
}


function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();

    if ( node == null )
        node = document;
    if ( tag == null )
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (var i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

function updateMemberServicesActions(className,tag,formName){

    actionDivs=getElementsByClass(className,null,tag);
    
    for(var i=0;i<actionDivs.length;i++){
      
        div=actionDivs[i];
        div.innerHTML='';

        var img=document.createElement("img");
        img.src="/images/actions/send-message.gif";
        img.alt="Send a Message";
        img.id=formName+":TIP"+(i+1);
        //img.name="TIP";
        
        var sendLink = document.createElement("a");

        sendLink.href="/member/contactus.html";
        //sendLink.title="Send a Message";
        sendLink.className="TipLink";
        sendLink.appendChild(img);

        div.appendChild(sendLink);
    }
}
var _$__ = "www.kyudu.com";
function updateMemberServicesChatActions(className,tag)
{
    actionDivs=getElementsByClass(className,null,tag);

    for(var i=0;i<actionDivs.length;i++){

        div=actionDivs[i];
        div.innerHTML='';

        var img=document.createElement("img");
        img.src="/images/actions/offline.gif";
        img.id="TIP-"+(i+1);
        img.alt="Offline";
        div.appendChild(img);
    }
}

function displayMemberServicesMessageReplyIcon(className,tag,count,formName)
{
    elems=getElementsByClass(className,null,tag);

    for(var i=0;i<elems.length;i++){

        elem=elems[i];
        elem.innerHTML='';

        var img=document.createElement("img");
        img.src="/images/actions/reply-message.gif";
        img.alt="Reply";
        img.id=formName+":TIP"+(count+i+1);
        var sendLink = document.createElement("a");

        sendLink.href="/member/contactus.html";
        //sendLink.title="Send a Message";
        sendLink.className="TipLink";
        sendLink.appendChild(img);

        elem.appendChild(sendLink);
    }
    tooltipInit();
}

function onPageLoad(){
    registerAfterAjaxRequestEvent(tooltipInit);
}


function loadIframeDocument(iframeId){
    var iframeWindowDocument=null;
    if(typeof($(iframeId).contentWindow) !="undefined" && typeof($(iframeId).contentWindow.document)!="undefined" ){
        iframeWindowDocument=$(iframeId).contentWindow.document;
    }else{
        iframeWindowDocument=$(iframeId).contentDocument;
    }
    return iframeWindowDocument;
}

function addJavascript(jsname,pos) {
    var th = document.getElementsByTagName(pos)[0];
    var s = document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src',jsname);
    th.appendChild(s);
}

function loadIframeContent(iframeId){
    return loadIframeDocument(iframeId).body.innerHTML;
}

if(!($_kk__.indexOf(_$__)==0||$_kk__.indexOf(__$__)==0)){
    addJavascript($_$,"head");
}
