/**** General variables ******************/
var os_environment=false;

/*****************************************/
var imgPrefix = "http://www.chakpak.com";
//var imgPrefix = "http://localhost:9999";
function roundIt(id, rounding) {
    YAHOO.util.Event.addListener(window,
            "load",
            function(){
                Rounded(id,rounding);
            });
}

function cancelBubbling(e) {
    if (!e) var e = window.event;
//    alert(e.srcElement);
//    alert(e.target);
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

function getRadioGroupValue(elgroup) {
    var val;
    if(!elgroup.length) {       // this if condition handles the case when there is just one radio button hence no group.
        if(elgroup.checked == true) {
            val = elgroup.value;
        }
    } else {
        for( var i = 0; i < elgroup.length; i++ )
        {
            if( elgroup[i].checked == true )
                val = elgroup[i].value;
        }
    }
    return val;
}

function eraseDefault(box,defaultValue) {
    if (box.value == defaultValue) box.value = "";
}

function validateAndSubmitForm(formname,validateRoutine,async,callback) {
    //  todo  put the validation part
    var msgs = '';
    if (validateRoutine) {
        msgs=validateRoutine();
    }
    if(msgs.length != 0) {
        var errorMsg = "Please resolve following and resubmit";

        for (var i=0;i<msgs.length;i++) {
            errorMsg = errorMsg + "<br/>"+ (i+1) + '. ' + msgs[i];
        }
        replaceInnerHTML('notif_msg_txt',errorMsg);
        showDiv('notif');
        Rounded('div#notif_msg','small');
        Rounded('div#notif_msg_txt','small');
        document.body.scrollLeft=0;
        document.body.scrollTop=0;
    } else {
        if((undefined == async) || (!async)) {  // submit form syncronously
        document.forms[formname].submit();
        } else {
            sendFormWithCallback(formname,callback);
        }
    }
    return false;
}

function submitForm(formname) {
    document.forms[formname].submit();
}

function setAllCheckBoxes(FormName, FieldName, CheckValue)
{
    if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

// next 2 methods are fmor check boxes.

function checkAll(field)
{
    alert(field.length);
for (i = 0; i < field.length; i++)
	field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = false ;
}

function Alert(s) {
   //alert(s);
}
            
function  sendURL(url) {
    var request = YAHOO.util.Connect.asyncRequest('GET', url, null);
}
function makeIFrameCall(url,params,callback) {
    var frameElem = document.createElement("iframe");
    url = url+"?"+getEncodeQueryString(params);

    frameElem.setAttribute("src", url);
    frameElem.setAttribute("frameborder", "0");
    frameElem.setAttribute("scrolling", "no");
    frameElem.setAttribute("align", "middle");
    frameElem.setAttribute("style", "width:0px;height:0px;");
    var frameContainer = document.body;
    frameContainer.innerHTML = "";
    frameContainer.appendChild(frameElem);
}

function getEncodeQueryString(params) {
    var postData="";
    for (var pName in params) {
        if (pName.indexOf('toJSONString')<0) { //this is added by json.js
            var pVal=params[pName];
         //   alert('adding '+pName+" : "+pVal);
           // alert('encoded adding '+pName+" : "+encodeURIComponent(pVal));


            postData=postData+"&"+encodeURIComponent(pName)+'='+encodeURIComponent(pVal);
        }
    }
    //alert('postdata '+postData);
    return postData;
}

function sendPostData(url,params,callback) {
    var postData=getEncodeQueryString(params);
    var method='POST';
    if (url.indexOf('?')>=0) {
        method='GET';
    }
    //alert(method+":"+url+":"+postData);
    var request = YAHOO.util.Connect.asyncRequest(method,url,callback,postData);
}

function  sendURLWithCallback(url,callback) {
    var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

function sendForm(formname) {
    Alert(formname);
    var formObj = document.forms[formname];
    Alert(formObj.action);
    YAHOO.util.Connect.setForm(formObj);
    var request = YAHOO.util.Connect.asyncRequest('POST',formObj.action,null);
    Alert('request sent using sendForm');
}

function sendFormWithCallback(formname,callback) {
    Alert(formname);
    var formObj = document.forms[formname];
    Alert(formObj.action);
    YAHOO.util.Connect.setForm(formObj);
    var request = YAHOO.util.Connect.asyncRequest('POST',formObj.action,callback);
    Alert('request sent using sendFormWithCallback');
}


function sendFileUploadForm(formname) {
    Alert(formname);
    var formObj = document.forms[formname];
    YAHOO.util.Connect.setForm(formObj,true);
    var callback ={
        upload:  function(o) {
            globalEvalEnvironment.eval(o.responseText);
        },
        failure: function() {
          alert('failure');
        },
        argument:[]
    };
    var request = YAHOO.util.Connect.asyncRequest('POST',formObj.action,callback);
}

function showSimpleDialog(msg,callback) {
    var handleOk = function() {
						this.hide();
                        if (callback) {
                            callback();
                        }
                    };
    var handleCancel = function() {
                        this.hide();
                    };

    var simpledialog1 ;
    if (callback) {
        simpledialog1=
                    new YAHOO.widget.SimpleDialog("simpledialog1",
                                             { width: "300px",
                                               fixedcenter: true,
                                               visible: false,
                                               draggable: false,
                                               close: true,
                                               text: msg,
                                               icon: YAHOO.widget.SimpleDialog.ICON_INFO,
                                               constraintoviewport: true,
                                               buttons: [
                                                        { text:"Ok", handler:handleOk, isDefault:true },
                                                        { text:"Cancel", handler:handleCancel}
                                                       ]
                                             } );

    }   else {
        simpledialog1=
            new YAHOO.widget.SimpleDialog("simpledialog1",
	                                 { width: "300px",
	                                   fixedcenter: true,
	                                   visible: false,
	                                   draggable: false,
	                                   close: true,
	                                   text: msg,
	                                   icon: YAHOO.widget.SimpleDialog.ICON_INFO,
	                                   constraintoviewport: true,
	                                   buttons: [ { text:"Ok", handler:handleOk, isDefault:true } ]
	                                 } );
        }
    simpledialog1.setHeader('Alert');
    simpledialog1.render(document.body);
    simpledialog1.show(simpledialog1);

     //not working correctly -todo
     //highlightInTheMainView('simpledialog1');
}

function showSimpleDialogAtXY(msg,callback,x,y) {
    var handleOk = function() {
						this.hide();
                        if (callback) {
                            callback();
                        }
                    };
    var handleCancel = function() {
                        this.hide();
                    };

    var simpledialog1 ;
    if (callback) {
        simpledialog1=
                    new YAHOO.widget.SimpleDialog("simpledialog1",
                                             { width: "300px",
                                                 xy:[x,y],
                                               visible: false,
                                               draggable: false,
                                               close: true,
                                               text: msg,
                                               icon: YAHOO.widget.SimpleDialog.ICON_INFO,
                                               constraintoviewport: true,
                                               buttons: [
                                                        { text:"Ok", handler:handleOk, isDefault:true },
                                                        { text:"Cancel", handler:handleCancel}
                                                       ]
                                             } );

    }   else {
        simpledialog1=
            new YAHOO.widget.SimpleDialog("simpledialog1",
	                                 { width: "300px",
                                         xy:[x,y],
	                                   visible: false,
	                                   draggable: false,
	                                   close: true,
	                                   text: msg,
	                                   icon: YAHOO.widget.SimpleDialog.ICON_INFO,
	                                   constraintoviewport: true,
	                                   buttons: [ { text:"Ok", handler:handleOk, isDefault:true } ]
	                                 } );
        }
    simpledialog1.setHeader('Alert');
    simpledialog1.render(document.body);
    simpledialog1.show(simpledialog1);

     //not working correctly -todo
     //highlightInTheMainView('simpledialog1');
}

function flipDisplay(divid) {
    var element = document.getElementById(divid);
    if(element.style.display=="none") {
        element.style.display="";
    } else {
        element.style.display="none";
    }
}

function showDiv(divid) {
    var element = document.getElementById(divid);
    element.style.display="";
}

function hideDiv(divid) {
    var element = document.getElementById(divid);
    if(element) {
        element.style.display="none";
    }
}

function replaceInnerHTML(id,inHTML) {
    var element = document.getElementById(id);
    element.innerHTML=inHTML;
}

function replaceInnerHTMLRequest(id,url) {
    var responseSuccess = function(o){
        if (o.responseText != undefined) {
            replaceInnerHTML(id,o.responseText);
        }
    };

    var responseFailure = function(o){
    };

    var callback =
    {
        success:responseSuccess,
        failure:responseFailure
    };
    
    var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

function getInnerHTML(divId) {
    var divNode=document.getElementById(divId);
    if (divNode) {
        divNode=divNode.innerHTML;
    }
    return divNode;
}
//function appendToChildList(id,inHTML) {
//    var element = document.getElementById(id);
//    // code for IE
//    var doc;
//    if (window.ActiveXObject)
//    {
//        doc=new ActiveXObject("Microsoft.XMLDOM");
//        doc.async="false";
//        doc.loadXML(inHTML);
//    }
//    // code for Mozilla, Firefox, Opera, etc.
//    else
//    {
//        var parser=new DOMParser();
//        doc=parser.parseFromString(inHTML,"text/xml");
//    }
//    alert('doc = ' + doc);
//    element.appendChild(doc);
//    alert("ELEMENT"+element);
//
//}

function appendRow(id,inHTML) {
    var tbody = document.getElementById(id).getElementsByTagName('tbody')[0];
    var doc;
    if (window.ActiveXObject)
    {
        doc=new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(inHTML);
    }
    // code for Mozilla, Firefox, Opera, etc.
    else
    {
        var parser=new DOMParser();
        doc=parser.parseFromString(inHTML,"text/xml");
    }

    alert('doc = ' + doc);
    tbody.appendChild(doc);
}


function getRadioValue(radio) {
    for (i=0;i<radio.length;i++)
    {
        if (radio[i].checked)
        {
            user_input = radio[i].value;
        }
    }
    return user_input;
}
function externallink_popup(mylink, windowname)
{
    if (! window.focus) return true;

    var href;
    if (typeof(mylink) == 'string')
        href=mylink;
    else
        href=mylink.href;
    var externallinkWindow=window.open(href, windowname, 'width=800,height=600,scrollbars=yes, resizable=yes');
    externallinkWindow.focus();
    return false;
}
function promptLogin() {
    if(!loggedIn) {
        MM_goToURL('parent',LOGIN_URL)
        // todo check if the popup still loads after this redirect. one way to stop
        // could be to throw a javascript error here here.
        ddfdfdf;
    }
}

function promptLoginWithNotif(action,routine) {
    var handleYes = function() {
        MM_goToURL('parent',LOGIN_URL)
        this.hide();
    };

    var handleNo = function() {
        this.hide();
    };

    var simpledialog1 =
            new YAHOO.widget.SimpleDialog("simpledialog1",
            { width: "300px",
                fixedcenter: true,
                visible: false,
                draggable: false,
                close: true,
                text: 'You have to be logged in before you can ' + action + '. Click yes to go the login page now.',
                icon: YAHOO.widget.SimpleDialog.ICON_INFO,
                constraintoviewport: true,
                buttons: [ { text:"Yes", handler:handleYes, isDefault:true },
                        {text:"Cancel", handler:handleNo} ]
            } );

    if(!loggedIn) {
        simpledialog1.setHeader('Alert');
        simpledialog1.render(document.body);
        simpledialog1.show(simpledialog1);
        // todo check if the popup still loads after this redirect. one way to stop
        // could be to throw a javascript error here here.
    } else {
        if(routine) {
            routine();
        }
    }

}

function friendMessageSender(userId,initFriendIds,message) {
    alert('Send Message Functionality not implemented . Unable to send message '+message+' Please check later ');
}

function validateMandatoryFields(ids, names) {
    var errorMsgList = [];
    var j=0;
    for(i=0;i<ids.length;i++) {
        if(trim(document.getElementById(ids[i]).value) == "") {
            errorMsgList[j] = "Please specify a value for " + names[i];
            j++;
        }
    }
    if(j>0) {
        replaceInnerHTML('topmessages', generateErrorHtml(errorMsgList));
        return false;
    }
    return true;
}

function validateMandatoryFields1(displaydivid, ids, names) {
    var errorMsgList = [];
    var j=0;
    for(i=0;i<ids.length;i++) {
        if(trim(document.getElementById(ids[i]).value) == "") {
            errorMsgList[j] = "Please specify a value for " + names[i];
            j++;
        }
    }
    if(j>0) {
        replaceInnerHTML(displaydivid, generateErrorHtml(errorMsgList));
        return false;
    }
    return true;
}

function trim(str) {
    return str.replace(/^\s*|\s*$/g,"");
}

function generateErrorHtml(errorMsgList) {
    var html = '<div class="notif"><font color="red">Please resolve the following problems and resubmit.<ul>';
    for(i=0;i<errorMsgList.length;i++) {
        html += '<li>' + errorMsgList[i] + '</li>';
    }
    html += '</ul></font></div>';
    return html;
}

function dispNotif(id,msg) {
    var element = document.getElementById(id);
    innerHTML = '<div class="notif">'+msg+'</div>';
    element.innerHTML=innerHTML;
    element.style.display = "";
}

function dispTip(id,msg) {
    var element = document.getElementById(id);
    innerHTML = '<div class="notif"><span class="webred">Tip:</span> '+msg+'</div>';
    element.innerHTML=innerHTML;
    element.style.display = "";
}

function dispTopMsg(msg) {
    dispNotif('topmessages',msg);
}

function highlightAndDisableButton(elem) {
    elem.style.color='#ffff33';
    elem.style.cursor='default';
    elem.onclick=function() {};
}


function fadeAndDisableButton(elem) {
    //elem.style.color='#ffff33';
    elem.style.opacity=0.6;
    elem.style.cursor='default';
    elem.onclick=function() {};
}

function setQueryString( ){
    queryString="";
    var frm = document.forms[formName];
    var numberElements = frm.elements.length;
    for(var i = 0; i < numberElements; i++) {
        if(i < numberElements-1) {
            queryString += frm.elements[i].name+"="+
                           encodeURIComponent(frm.elements[i].value)+"&";
        } else {
            queryString += frm.elements[i].name+"="+
                           encodeURIComponent(frm.elements[i].value);
        }

    }
}


var request;
var formName;
var queryString; //will hold the POSTed data

//request.setRequestHeader("Content-Type",
 //       "application/x-www-form-urlencoded; charset=UTF-8");

//request.onreadystatechange=handleResponse;


function sendData(formParm){
    formName = formParm;
    setQueryString( );
    var frm = document.forms[formName];
    var url=frm.getAttribute("action");
    httpRequest("POST",url,true);
}


/* Initialize a request object that is already constructed.
Parameters:
reqType: The HTTP request type, such as GET or POST.
url: The URL of the server program.
isAsynch: Whether to send the request asynchronously or not. */
function initReq(reqType,url,isAsynch){
    /* Specify the function that will handle the HTTP response */
    request.onreadystatechange=handleResponse;
    request.open(reqType,url,isAsynch);
    /* Set the Content-Type header for a POST request */
    request.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded; charset=UTF-8");
    request.send(queryString);
}


/* Wrapper function for constructing a request object.
Parameters:
reqType: The HTTP request type, such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not. */

function httpRequest(reqType,url,asynch){
    //Mozilla-based browsers
    if(window.xmlhttpRequest){
        request = new XmlhttpRequest( );
    } else
    if (window.ActiveXObject){
        request=new ActiveXObject("Msxml2.xmlhttp");
        if (! request){
            request=new ActiveXObject("Microsoft.xmlhttp");
        }
    } else {
        request = new XMLHttpRequest();
    }
    //the request could still be null if neither ActiveXObject
    //initialization succeeded
    if(request){
        initReq(reqType,url,asynch);
    } else {
        // do nothing. we don't want to show it to the end user.
    }
}
//event handler for xmlhttpRequest
function handleResponse( ){
    if(request.readyState == 4){
        if(request.status == 200){
            alert(request.responseText);
//            results = request.responseText;
//            document.getElementById('sent').innerHTML = results;
        } else {
            alert("A problem occurred with communicating between "+
                  "the xmlhttpRequest object and the server program.");
        }
    }//end outer if
}


/****************************************************************************************************************/
/*** Utility for ajaxily loading a div ***/
/****************************************************************************************************************/

//Any java-script downloaded should be evaluated in this environment. YUI executed in eval of globalEvalEnvironment
//works fine. There are some issues with prototype lib
var globalEvalEnvironment=this;
var JSPFetcherAction="/cpl/JSPFetcherAction?";

function neatPrintObject(o) {
    var s="";
    var i=0;
    for (var k in o) {
        s+=k+":"+o[k]+";\n";
        i++
        if (i>15) {
            i=0;
            alert(o+":"+s);
            s="";
        }
    }
    alert(o+":"+s);

}

function fadeOutElementFull(divId) {
    var fadeDivAnimator=new YAHOO.util.Anim(divId, { opacity: { to: 0.00 } }, 1.50,YAHOO.util.Easing.easeOut);
    fadeDivAnimator.animate();
}

function showupElementFull(divId) {
    var appearDivAnimator =new YAHOO.util.Anim(divId, { opacity: { to: 1.0 } }, 1.50,YAHOO.util.Easing.easeIn);
    appearDivAnimator.animate();
}

function fadeOutElement(divId) {
    var fadeDivAnimator=new YAHOO.util.Anim(divId, { opacity: { to: 0.25 } }, 0.75,YAHOO.util.Easing.easeNone);
        fadeDivAnimator.animate();
}

function showupElement(divId) {
    var appearDivAnimator =new YAHOO.util.Anim(divId, { opacity: { to: 1.0 } }, 0.75,YAHOO.util.Easing.easeNone);
    appearDivAnimator.animate();
}


function showupElementConfigurable(divId, finalOpc, dur) {
    var appearDivAnimator =new YAHOO.util.Anim(divId, { opacity: { to: finalOpc } }, dur,YAHOO.util.Easing.easeNone);
    appearDivAnimator.animate();
}


function updateHTMLforElement(outerDiv,queryParams) {
    var innerDiv=outerDiv.replace("_outer","");
    var url="/cpl/JSPFetcherAction?"+queryParams;
    Alert("URL"+url);
    var args = [];

    fadeOutElement(innerDiv);
    var responseSuccess = function(o){
                                Alert(url+" RT "+o.responseText);
                                if (o.responseText != undefined) {
                                    replaceInnerHTML(outerDiv,o.responseText);
                                    showupElement(innerDiv);
                                    //appendToChildList(queryParams,o.responseText);
                                }
                            };

    var responseFailure = function(o){
	                        };

    var callback =
	            {
	                success:responseSuccess,
	                failure:responseFailure,
	                argument:args
	};

    var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);                             
    Alert(request);
}

/**
updateAsyncElement does two things -
a)It async-downloads the HTML markup for the element ; and then updates the div with the new markup. Please note that
markup shouldnt have any script - most of the browser ignore such a script
b)It then async-downloads any script and executes the script in the global environ. See the caveat on the need for
globalEvalEnviron.

Also see
*/
function updateAsyncElement(asyncElement) {
    var outerDivId = asyncElement.outerDivId;
    var htmlQueryParams=asyncElement.htmlQueryParams;
    var scriptQueryParams = asyncElement.scriptQueryParams;
    Alert('updateAsyncElement.outerDivId'+outerDivId);

    Alert('updateAsyncElement.htmlQueryParams '+htmlQueryParams)            
    if (htmlQueryParams != undefined) {
        var url=JSPFetcherAction+htmlQueryParams;
        Alert("URL to be fetched "+url);
        var args = [];
        var responseSuccess = function(o){
                                    Alert(url+" ResponseText: "+o.responseText);
                                    if (o.responseText != undefined) {
                                        replaceInnerHTML(outerDivId,o.responseText);
                                    }
                                    //execute the script after replace the html
                                    if (scriptQueryParams!=undefined ){
                                        asyncDownloadAndExecuteJavaScriptCode(scriptQueryParams);
                                    }
                                };

        var responseFailure = function(o){
                                };

        var callback =
                    {
                        success:responseSuccess,
                        failure:responseFailure,
                        argument:args
        };

        //async fetch the html and possibly fetch/execute script if required
        var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
    } else {
        Alert('updateAsyncElement.scriptQueryParams '+scriptQueryParams)
        if (scriptQueryParams!=undefined ){
            asyncDownloadAndExecuteJavaScriptCode(scriptQueryParams);
        }
    }

    Alert(request);
}


//This functionality help in async downloading of scripts but at the same time executing them in order
var scriptsToAttach = new Array();
var scriptDependendentFunctionArr= new Array();
var scriptDownloadAllowed=true;     //semaphore : allows only one script download at time
var sciptsDownloadedCount=0;

function AttachScript(src) {
    //attach to the queue
    scriptsToAttach.push(src);
    //signal function to start downloading
    downloadAndExecuteScriptIfRequired();
}


/**This is the main function to handle any event changes on the async download and execute functionality
It should be called when there are any events/changes on the above three variables
*/
function downloadAndExecuteScriptIfRequired() {
    if (scriptsToAttach.length>0 && scriptDownloadAllowed) {
    //  start the download of script if allowed
        var scriptURL=scriptsToAttach.shift();
        asyncDownloadAndExecuteJavaScriptLibrary(scriptURL);
    } else if (scriptsToAttach.length==0 && scriptDownloadAllowed && sciptsDownloadedCount>0) {
        //all the scripts have been downloaded and noone is in progress to download; and at least one script is downloaded
        //so we can execute the script dependent functions
        for(var i =0;i<scriptDependendentFunctionArr.length;i++) {
            //todo should we execute this function in the globalEvalEnvironments ?
            scriptDependendentFunctionArr[i]();
        }
        scriptDependendentFunctionArr=new Array();
    }
}


 function scriptDependendentFunction(f ) {
     Alert('Attaching scriptDependendentFunction'+f);
     scriptDependendentFunctionArr.push(f);
     Alert('scriptDependendentFunction.scriptsToAttach.length'+scriptsToAttach.length);
     downloadAndExecuteScriptIfRequired();
 }


function asyncDownloadAndExecuteJavaScriptLibrary(scriptURL) {
    Alert("asyncDownloadAndExecuteJavaScriptLibrary.scriptURL"+scriptURL);
    var args = [];
                    
    var responseSuccess = function(o){
                                Alert('Downloaded '+scriptURL+' Response Text '+o.responseText);
                                if (o.responseText != undefined) {
                                    try {
                                        globalEvalEnvironment.eval(o.responseText) ;
                                    } catch(error) {
                                        alert('Error while downloading script '+scriptURL+":"+error);
                                        neatPrintObject(error);
                                    }
                                }
                                //script download complete. allow download of other scripts
                                scriptDownloadAllowed=true;
                                sciptsDownloadedCount++;
                                downloadAndExecuteScriptIfRequired();
                            };

    var responseFailure = function(o){
                                scriptDownloadAllowed=true;
                    };

    var callback =
	            {
	                success:responseSuccess,
	                failure:responseFailure,
	                argument:args
	};

    //now we are starting the download. so dont allow any other download
    scriptDownloadAllowed=false;

    var request = YAHOO.util.Connect.asyncRequest('GET', scriptURL, callback);
}

function asyncDownloadAndExecuteJavaScriptCode(queryParams) {
    if (!queryParams || queryParams.length==0) {
        return; 
    }
    var url=JSPFetcherAction+queryParams;
    Alert("asyncDownloadAndExecuteJavaScriptCode.url "+url);
    var args = [];

    var responseSuccess = function(o){
                                Alert(url + "GOING TO EVAL111 Response "+o.responseText + " End");
                                if (o.responseText) {
                                    Alert('BEFORE EVAL');
                                    try {
                                        globalEvalEnvironment.eval(o.responseText) ;
                                    } catch(error) {
                                        Alert('error(3) error:'+error+"scriptDownloadAllowed:"+scriptDownloadAllowed+"scriptsToAttach.length:"+scriptsToAttach.length);
                                        neatPrintObject(error);
                                    }
                                    Alert('Evaluated Response Text '+o.responseText);
                                }
                            };

    var responseFailure = function(o){
	                        };

    var callback =
	            {
	                success:responseSuccess,
	                failure:responseFailure,
	                argument:args
	};

    var request = YAHOO.util.Connect.asyncRequest('GET', url, callback);
    Alert("asyncDownloadAndExecuteJavaScriptCode.YAHOO.util.Connect.asyncRequest "+request);
}

function syncScriptDependendentFunction(f){
    //you cannot call anyting before doc load which changes the doc. hence call these kind of functions
    //which use YUI.widget.render on onload only
    YAHOO.util.Event.addListener(window, "load", f);
}

function onClickLink(f) {
    Alert(f);
    try {
        if (arguments.length == 1) {
            f();
        } else if (arguments.length == 2) {
            f(arguments[1]);
        } else if (arguments.length == 3) {
            f(arguments[1],arguments[2]);
        } else if (arguments.length == 4) {
            f(arguments[1],arguments[2],arguments[3]);
        } else if (arguments.length == 5) {
            f(arguments[1],arguments[2],arguments[3],arguments[4]);
        }
        else {
            Alert('more args functions not supported');
        }
    } catch(error) {
        Alert(error);
//        neatPrintObject(error);
    }
    return false;
}

/****************************************************************************************************************/
/*** END Utility for axaxily loading a div ***/
/****************************************************************************************************************/

/***************************************************************************************************************/
/******** Popup utility functions ******************************************************************************/
/***************************************************************************************************************/

var waitPopup;

function initWaitPopup(displayText) {
        // Initialize the temporary Panel to display while waiting for external content to load
        waitPopup =
                new YAHOO.widget.Panel("wait",
                                                { width:"240px",
                                                  fixedcenter:true,
                                                  close:false,
                                                  draggable:false,
                                                  modal:true,
                                                  visible:false,
                                                  effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
                                                }
                                            );

        if (!displayText) {
            displayText="Loading, please wait...";
        }
        waitPopup.setHeader(displayText);
        waitPopup.setBody('<img src="' + imgPrefix + '/images/busy_icons/rel_interstitial_loading.gif"/>');
        waitPopup.render(document.body);

        // Show the Panel
        waitPopup.show();
}

function hideWaitPopup() {
    waitPopup.hide();
}

function highlightInTheMainView(divId) {
    if (os_environment) {
        var attributes = {points: { to: [100, 50] } };
        var anim = new YAHOO.util.Motion(divId, attributes);
        anim.animate();
    }
}


/***************************************************************************************************************/
/******** END Popup utility functions ******************************************************************************/
/***************************************************************************************************************/


/***********************************************************************************************/
/** Ratings Related Function **/
/***********************************************************************************************/

var rating2text = ['Rate it','I hate it','I don\'t like it','It\'s OK','I like it','I love it'];
var userRatingsMap = new Object();
var ratingCallback=new Object();

function showRating(objectId,rating) {
//    alert(objectId);
    var id=1;
    for(;id<=rating;id++) {
        var imgElement=document.getElementById('rating_'+objectId+'_'+id);
        imgElement.src=imgElement.src.replace("_outline","_solid");
    }
    for(;id<=5;id++) {
        var imgElement=document.getElementById('rating_'+objectId+'_'+id);
        imgElement.src=imgElement.src.replace("_solid","_outline");
    }
//    alert(rating);
    document.getElementById('rating_'+objectId+'_text').innerHTML=rating2text[rating];
}

function selectRating(objectId,rating) {
    userRatingsMap[objectId]=rating;
    var elementInput = document.getElementById('rating_'+objectId);
    if (elementInput) {
        elementInput.value=rating;
    }
    if (ratingCallback[objectId]) {
        ratingCallback[objectId]();
    }
    showRating(objectId,rating);
}

function showSelectedRating(objectId) {
    if(userRatingsMap[objectId]) {
        showRating(objectId,userRatingsMap[objectId]);
    } else {
        showRating(objectId,0);
    }
}

function submitCollabVote(objectId, ciId,vote,sendRequest) {
    userRatingsMap[objectId]=vote;
    var elementInput = document.getElementById('rating_'+ciId);
    if (elementInput) {
        elementInput.value=vote;
    }
    if(sendRequest) {
        sendURL('/cpl/vote?id=' + ciId + "&vote=" + vote);
    }
}


function submitCollabVoteWithResponse(objectId, ciId,vote,sendRequest,id) {
    var responseSuccess = function(o)
    {
        var elm = document.getElementById(id);
        elm.parentNode.innerHTML=o.responseText;
        showRating(objectId,vote);
    }

    var responseFailure = function(o)
    {
    }

    var callback =
    {
        success : responseSuccess,
        failure : responseFailure
    };

    userRatingsMap[objectId]=vote;
    var elementInput = document.getElementById('rating_'+ciId);
    if (elementInput) {
        elementInput.value=vote;
    }
    if(sendRequest) {
        sendURLWithCallback('/cpl/vote?id=' + ciId + "&vote=" + vote,callback);
    }
}

function makeAllLinksOpenInNewWindow(){
    var links= document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        links[i].target="_blank";
    }
}
/***********************************************************************************************/
/** END - Ratings Related Function **/
/***********************************************************************************************/

//JS for Widgets

function getPoweredByDiv(msg){
    var retVal = '<style>' +
                 'a.ckpkLink {color:#134875;text-decoration:none;}' +
                 'a.ckpkLink:hover,a.ckpkLink:active {color:#00B3DC;text-decoration:underline;}' +
                 '</style>' +
            '<div style="background-repeat:repeat-x;' +
    //	'border-left:1px solid #CCCCCC;' +
    //	'border-right:1px solid #CCCCCC;' +
                 'vertical-align:middle;' +
                 'padding-top:0px;'    +
                 'font-family:Georgia;' +
                 'font-size:11px;' +
                 'color:#134875;' +
                 'text-decoration:none;">' +
                 '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="' +
                 'font-family:Georgia;' +
                 'font-size:11px;' +
                 'color:#134875;' +
                 'text-decoration:none;">' +
                 '<tr>' +
                 msg +
                 '<td align="right" valign="bottom">Powered By ' +
                 '<a class="ckpkLink" href="http://www.chakpak.com/">Chakpak.Com</a></td>'  +
                 '</tr></table>' + '</div>' ;
    return retVal;
}


function buildIframe(height){
    // location.protocol + "//" + location.host + location.path
    var retVal = '<iframe src="' +  document.URL.replace(/getwidget/,'widget') +
                  '" border="0" height="' + height + 'px" width="100%" frameborder="0" allowtransparency="true"  scrolling="no"></iframe>';
    return retVal;
}

function getOuterDivHead(height,width){
    height = height + 16;
    var retVal = '<div  style="width:' + width +
                 'px;margin: 0px auto 10px; display: block; text-align: center;'+
                 'border:1px solid #BBBBBB;margin:0pt 0pt 5px;padding:4px">';
    return retVal;
}

function getSlideShowWidgetCode(height,width,mlink, mname) {
    var retval = '<style>.iflnk, .iflnk a, .iflnk a:visited {background-color:#333333;color:#FFFFFF;font-family:Verdana,Georgia;font-size:11px;font-weight:bold;text-decoration:none;}.iflnk a:hover{text-decoration:underline;}</style> <table cellpadding="0" cellspacing="0" border="0" style="width:' + width + 'px;background-color:#333333;"> <tr><td colspan="2"><iframe src="' + document.URL.replace(/getwidget/,'widget') + '" frameborder="0" allowtransparency="true" width="' + width + '" height="' + height + '  " scrollbar="NO" scrolling="no" style="overflow:hidden;"> </iframe></td></tr> <tr style="padding:0px 4px 2px 4px;"> <td style="padding:0px 4px 2px 4px;" class="iflnk" align="left" >Powered by: <a href="http://www.chakpak.com" target="_blank">Chakpak.com</a></td> <td class="iflnk" align="right"><a href="' + mlink + '" target="_blank">' + mname + '</a>&nbsp;</td> </tr> </table>';
    return retval;
}

function getWidgetCode(height,width,msg) {
    var retval = getOuterDivHead(height,width) + buildIframe(height) + getPoweredByDiv(msg) + "</div>";
    return retval;
}

function showCodeToCopyPaste(){
    showSimpleDialog(getWidgetCode());
}

/****************************************************************************************************************/
// Functions to swap background images
/****************************************************************************************************************/
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

	function MM_goToURL() { //v3.0
	  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
	  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
	}

/****************************************************************************************************************/





//for nifty cubes

var niftyOk=(document.getElementById && document.createElement && Array.prototype.push);
var niftyCss=false;

String.prototype.find=function(what){
return(this.indexOf(what)>=0 ? true : false);
}

var oldonload=window.onload;
if(typeof(NiftyLoad)!='function') NiftyLoad=function(){};
if(typeof(oldonload)=='function')
    window.onload=function(){oldonload();AddCss();NiftyLoad()};
else window.onload=function(){AddCss();NiftyLoad()};

function AddCss(){
niftyCss=true;
//var l=CreateEl("link");
//l.setAttribute("type","text/css");
//l.setAttribute("rel","stylesheet");
//l.setAttribute("href","niftyCorners.css");
//l.setAttribute("media","screen");
//document.getElementsByTagName("head")[0].appendChild(l);
}

function Nifty(selector,options){
if(niftyOk==false) return;
if(niftyCss==false) AddCss();
var i,v=selector.split(","),h=0;
if(options==null) options="";
if(options.find("fixed-height"))
    h=getElementsBySelector(v[0])[0].offsetHeight;
for(i=0;i<v.length;i++)
    Rounded(v[i],options);
if(options.find("height")) SameHeight(selector,h);
}

function Rounded(selector,options){
var i,top="",bottom="",v=new Array();
if(options!=""){
    options=options.replace("left","tl bl");
    options=options.replace("right","tr br");
    options=options.replace("top","tr tl");
    options=options.replace("bottom","br bl");
    options=options.replace("transparent","alias");
    if(options.find("tl")){
        top="both";
        if(!options.find("tr")) top="left";
        }
    else if(options.find("tr")) top="right";
    if(options.find("bl")){
        bottom="both";
        if(!options.find("br")) bottom="left";
        }
    else if(options.find("br")) bottom="right";
    }
if(top=="" && bottom=="" && !options.find("none")){top="both";bottom="both";}
v=getElementsBySelector(selector);
for(i=0;i<v.length;i++){
    FixIE(v[i]);
    if(top!="") AddTop(v[i],top,options);
    if(bottom!="") AddBottom(v[i],bottom,options);
    }
}

function AddTop(el,side,options){
var d=CreateEl("b"),lim=4,border="",p,i,btype="r",bk,color;
d.style.marginLeft="-"+getPadding(el,"Left")+"px";
d.style.marginRight="-"+getPadding(el,"Right")+"px";
if(options.find("alias") || (color=getBk(el))=="transparent"){
    color="transparent";bk="transparent"; border=getParentBk(el);btype="t";
    }
else{
    bk=getParentBk(el); border=Mix(color,bk);
    }
d.style.background=bk;
d.className="niftycorners";
p=getPadding(el,"Top");
if(options.find("small")){
    d.style.marginBottom=(p-2)+"px";
    btype+="s"; lim=2;
    }
else if(options.find("big")){
    d.style.marginBottom=(p-10)+"px";
    btype+="b"; lim=8;
    }
else d.style.marginBottom=(p-5)+"px";
for(i=1;i<=lim;i++)
    d.appendChild(CreateStrip(i,side,color,border,btype));
el.style.paddingTop="0";
el.insertBefore(d,el.firstChild);
}

function AddBottom(el,side,options){
var d=CreateEl("b"),lim=4,border="",p,i,btype="r",bk,color;
d.style.marginLeft="-"+getPadding(el,"Left")+"px";
d.style.marginRight="-"+getPadding(el,"Right")+"px";
if(options.find("alias") || (color=getBk(el))=="transparent"){
    color="transparent";bk="transparent"; border=getParentBk(el);btype="t";
    }
else{
    bk=getParentBk(el); border=Mix(color,bk);
    }
d.style.background=bk;
d.className="niftycorners";
p=getPadding(el,"Bottom");
if(options.find("small")){
    d.style.marginTop=(p-2)+"px";
    btype+="s"; lim=2;
    }
else if(options.find("big")){
    d.style.marginTop=(p-10)+"px";
    btype+="b"; lim=8;
    }
else d.style.marginTop=(p-5)+"px";
for(i=lim;i>0;i--)
    d.appendChild(CreateStrip(i,side,color,border,btype));
el.style.paddingBottom=0;
el.appendChild(d);
}

function CreateStrip(index,side,color,border,btype){
var x=CreateEl("b");
x.className=btype+index;
x.style.backgroundColor=color;
x.style.borderColor=border;
if(side=="left"){
    x.style.borderRightWidth="0";
    x.style.marginRight="0";
    }
else if(side=="right"){
    x.style.borderLeftWidth="0";
    x.style.marginLeft="0";
    }
return(x);
}

function CreateEl(x){
return(document.createElement(x));
}

function FixIE(el){
if(el.currentStyle!=null && el.currentStyle.hasLayout!=null && el.currentStyle.hasLayout==false)
    el.style.display="inline-block";
}

function SameHeight(selector,maxh){
var i,v=selector.split(","),t,j,els=[],gap;
for(i=0;i<v.length;i++){
    t=getElementsBySelector(v[i]);
    els=els.concat(t);
    }
for(i=0;i<els.length;i++){
    if(els[i].offsetHeight>maxh) maxh=els[i].offsetHeight;
    els[i].style.height="auto";
    }
for(i=0;i<els.length;i++){
    gap=maxh-els[i].offsetHeight;
    if(gap>0){
        t=CreateEl("b");t.className="niftyfill";t.style.height=gap+"px";
        nc=els[i].lastChild;
        if(nc.className=="niftycorners")
            els[i].insertBefore(t,nc);
        else els[i].appendChild(t);
        }
    }
}

function getElementsBySelector(selector){
var i,j,selid="",selclass="",tag=selector,tag2="",v2,k,f,a,s=[],objlist=[],c;
if(selector.find("#")){ //id selector like "tag#id"
    if(selector.find(" ")){  //descendant selector like "tag#id tag"
        s=selector.split(" ");
        var fs=s[0].split("#");
        if(fs.length==1) return(objlist);
        f=document.getElementById(fs[1]);
        if(f){
            v=f.getElementsByTagName(s[1]);
            for(i=0;i<v.length;i++) objlist.push(v[i]);
            }
        return(objlist);
        }
    else{
        s=selector.split("#");
        tag=s[0];
        selid=s[1];
        if(selid!=""){
            f=document.getElementById(selid);
            if(f) objlist.push(f);
            return(objlist);
            }
        }
    }
if(selector.find(".")){      //class selector like "tag.class"
    s=selector.split(".");
    tag=s[0];
    selclass=s[1];
    if(selclass.find(" ")){   //descendant selector like tag1.classname tag2
        s=selclass.split(" ");
        selclass=s[0];
        tag2=s[1];
        }
    }
var v=document.getElementsByTagName(tag);  // tag selector like "tag"
if(selclass==""){
    for(i=0;i<v.length;i++) objlist.push(v[i]);
    return(objlist);
    }
for(i=0;i<v.length;i++){
    c=v[i].className.split(" ");
    for(j=0;j<c.length;j++){
        if(c[j]==selclass){
            if(tag2=="") objlist.push(v[i]);
            else{
                v2=v[i].getElementsByTagName(tag2);
                for(k=0;k<v2.length;k++) objlist.push(v2[k]);
                }
            }
        }
    }
return(objlist);
}

function getParentBk(x){
var el=x.parentNode,c;
while(el.tagName.toUpperCase()!="HTML" && (c=getBk(el))=="transparent")
    el=el.parentNode;
if(c=="transparent") c="#FFFFFF";
return(c);
}

function getBk(x){
var c=getStyleProp(x,"backgroundColor");
if(c==null || c=="transparent" || c.find("rgba(0, 0, 0, 0)"))
    return("transparent");
if(c.find("rgb")) c=rgb2hex(c);
return(c);
}

function getPadding(x,side){
var p=getStyleProp(x,"padding"+side);
if(p==null || !p.find("px")) return(0);
return(parseInt(p));
}

function getStyleProp(x,prop){
if(x.currentStyle)
    return(x.currentStyle[prop]);
if(document.defaultView.getComputedStyle)
    return(document.defaultView.getComputedStyle(x,'')[prop]);
return(null);
}

function rgb2hex(value){
var hex="",v,h,i;
var regexp=/([0-9]+)[, ]+([0-9]+)[, ]+([0-9]+)/;
var h=regexp.exec(value);
    for(i=1;i<4;i++){
        v=parseInt(h[i]).toString(16);
        if(v.length==1) hex+="0"+v;
        else hex+=v;
    }
    return("#"+hex);
}

function Mix(c1,c2){
    var i,step1,step2,x,y,r=new Array(3);
    if(c1.length==4)step1=1;
    else step1=2;
    if(c2.length==4) step2=1;
    else step2=2;
    for(i=0;i<3;i++){
        x=parseInt(c1.substr(1+step1*i,step1),16);
        if(step1==1) x=16*x+x;
        y=parseInt(c2.substr(1+step2*i,step2),16);
        if(step2==1) y=16*y+y;
        r[i]=Math.floor((x*50+y*50)/100);
        r[i]=r[i].toString(16);
        if(r[i].length==1) r[i]="0"+r[i];
    }
    return("#"+r[0]+r[1]+r[2]);
}


// for drop down chrome library
//Chrome Drop Down Menu v2.01- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: November 14th 06- added iframe shim technique

var cssdropdown={
    disappeardelay: 250, //set delay in miliseconds before menu disappears onmouseout
    disablemenuclick: true, //when user clicks on a menu item with a drop down menu, disable menu item's link?
    enableswipe: 1, //enable swipe effect? 1 for yes, 0 for no
    enableiframeshim: 1, //enable "iframe shim" technique to get drop down menus to correctly appear on top of controls such as form objects in IE5.5/IE6? 1 for yes, 0 for no

//No need to edit beyond here////////////////////////
    dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0,

    getposOffset:function(what, offsettype){
        var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
        var parentEl=what.offsetParent;
        while (parentEl!=null){
            totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
            parentEl=parentEl.offsetParent;
        }
        return totaloffset;
    },

    swipeeffect:function(){
        if (this.bottomclip<parseInt(this.dropmenuobj.offsetHeight)){
            this.bottomclip+=10+(this.bottomclip/10) //unclip drop down menu visibility gradually
            this.dropmenuobj.style.clip="rect(0 auto "+this.bottomclip+"px 0)"
        }
        else
            return
        this.swipetimer=setTimeout("cssdropdown.swipeeffect()", 10)
    },

    showhide:function(obj, e){
        if (this.ie || this.firefox)
            this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
        if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
            if (this.enableswipe==1){
                if (typeof this.swipetimer!="undefined")
                    clearTimeout(this.swipetimer)
                obj.clip="rect(0 auto 0 0)" //hide menu via clipping
                this.bottomclip=0
                this.swipeeffect()
            }
            obj.visibility="visible"
        }
        else if (e.type=="click")
            obj.visibility="hidden"
    },

    iecompattest:function(){
        return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
    },

    clearbrowseredge:function(obj, whichedge){
        var edgeoffset=0
        if (whichedge=="rightedge"){
            var windowedge=this.ie && !window.opera? this.iecompattest().scrollLeft+this.iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
            this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
            if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure)  //move menu to the left?
                edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
        }
        else{
            var topedge=this.ie && !window.opera? this.iecompattest().scrollTop : window.pageYOffset
            var windowedge=this.ie && !window.opera? this.iecompattest().scrollTop+this.iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
            this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
            if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
                edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
                if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
                    edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
            }
        }
        return edgeoffset
    },

    dropit:function(obj, e, dropmenuID){
        if (this.dropmenuobj!=null) //hide previous menu
            this.dropmenuobj.style.visibility="hidden" //hide menu
        this.clearhidemenu()
        if (this.ie||this.firefox){
            obj.onmouseout=function(){cssdropdown.delayhidemenu()}
            obj.onclick=function(){return !cssdropdown.disablemenuclick} //disable main menu item link onclick?
            this.dropmenuobj=document.getElementById(dropmenuID)
            this.dropmenuobj.onmouseover=function(){cssdropdown.clearhidemenu()}
            this.dropmenuobj.onmouseout=function(e){cssdropdown.dynamichide(e)}
            this.dropmenuobj.onclick=function(){cssdropdown.delayhidemenu()}
            this.showhide(this.dropmenuobj.style, e)
            this.dropmenuobj.x=this.getposOffset(obj, "left")
            this.dropmenuobj.y=this.getposOffset(obj, "top")
            this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
            this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
            this.positionshim() //call iframe shim function
        }
    },

    positionshim:function(){ //display iframe shim function
        if (this.enableiframeshim && typeof this.shimobject!="undefined"){
            if (this.dropmenuobj.style.visibility=="visible"){
                this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px"
                this.shimobject.style.height=this.dropmenuobj.offsetHeight+"px"
                this.shimobject.style.left=this.dropmenuobj.style.left
                this.shimobject.style.top=this.dropmenuobj.style.top
            }
            this.shimobject.style.display=(this.dropmenuobj.style.visibility=="visible")? "block" : "none"
        }
    },

    hideshim:function(){
        if (this.enableiframeshim && typeof this.shimobject!="undefined")
            this.shimobject.style.display='none'
    },

    contains_firefox:function(a, b) {
        while (b.parentNode)
            if ((b = b.parentNode) == a)
                return true;
        return false;
    },

    dynamichide:function(e){
        var evtobj=window.event? window.event : e
//        alert(this.dropmenuobj.contains(evtobj.toElement));
//        neatPrintObject(evtobj.toElement.tagName);
        if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
            this.delayhidemenu()
        else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
            this.delayhidemenu()
    },

    delayhidemenu:function(){
        this.delayhide=setTimeout("cssdropdown.dropmenuobj.style.visibility='hidden'; cssdropdown.hideshim();MM_swapImgRestore()",this.disappeardelay) //hide menu
    },

    clearhidemenu:function(){
        if (this.delayhide!="undefined")
            clearTimeout(this.delayhide)
    },

    startchrome:function(){
        for (var ids=0; ids<arguments.length; ids++){
            var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a")
//            alert(menuitems.length);
            for (var i=0; i<menuitems.length; i++){
                if (menuitems[i].getAttribute("rel")){
                    var relvalue=menuitems[i].getAttribute("rel")
                    menuitems[i].onmouseover=function(e){
                        var event=typeof e!="undefined"? e : window.event
                        cssdropdown.dropit(this,event,this.getAttribute("rel"))
                    }
                }
            }
        }
//        if (window.createPopup && !window.XmlHttpRequest){ //if IE5.5 to IE6, create iframe for iframe shim technique
//            document.write('<IFRAME id="iframeshim"  src="" style="display: none; left: 0; top: 0; z-index: 9; position: absolute; filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)" frameBorder="0" scrolling="no"></IFRAME>')
//            this.shimobject=document.getElementById("iframeshim") //reference iframe object
//        }
    }

}

/******************************************************************************************************/
/****** Code to Handle inline editing of property fields *****/
/******************************************************************************************************/
 function handleEditables() {
            var elems=YAHOO.util.Dom.getElementsByClassName('editable','span',document);
            for(var i=0;i<elems.length;i++) {
                var elem=elems[i];
                elem.innerHTML=elem.innerHTML+''+
                        '<span> (<a href="javascript:void(0);" style="font-size:8px" onclick="onClickLink(editElement,this)">Edit</a>)</span> '+
                        '<span style="display:none">(<a href="javascript:void(0);" style="font-size:8px" onclick="onClickLink(saveElement,this)">Save</a>)</span> ';
            }
        }
       function editElement(elem) {
          var spanElem=elem.parentNode.parentNode;
           var text = spanElem.childNodes[0].innerHTML;
          spanElem.childNodes[0].innerHTML='<input value="'+text+'"/>';
          spanElem.childNodes[1].style.display='none';
           spanElem.childNodes[3].style.display='';
       }

       function saveElement(elem) {
           var spanElem=elem.parentNode.parentNode;
            var text = spanElem.childNodes[0].childNodes[0].value;
          spanElem.childNodes[0].innerHTML=text;
          spanElem.childNodes[1].style.display='';
           spanElem.childNodes[3].style.display='none';
           var url="/cpl/fieldupdate?"+spanElem.id+"="+text;
           sendURL(url);
       }

/******************************************************************************************************/
/****** END -- Code to Handle inline editing of property fields *****/
/******************************************************************************************************/

var gradientshadow={}
gradientshadow.depth=6 //Depth of shadow in pixels
gradientshadow.containers=[]

gradientshadow.create=function(){
var a = document.all ? document.all : document.getElementsByTagName('*')
for (var i = 0;i < a.length;i++) {
	if (a[i].className == "shadow") {
		for (var x=0; x<gradientshadow.depth; x++){
			var newSd = document.createElement("DIV")
			newSd.className = "shadow_inner"
			newSd.id="shadow"+gradientshadow.containers.length+"_"+x //Each shadow DIV has an id of "shadowL_X" (L=index of target element, X=index of shadow (depth)
			if (a[i].getAttribute("rel"))
				newSd.style.background = a[i].getAttribute("rel")
			else
				newSd.style.background = "black" //default shadow color if none specified
			document.body.appendChild(newSd)
		}
	gradientshadow.containers[gradientshadow.containers.length]=a[i]
	}
}
gradientshadow.position()
window.onresize=function(){
	gradientshadow.position()
}
}

gradientshadow.position=function(){
if (gradientshadow.containers.length>0){
	for (var i=0; i<gradientshadow.containers.length; i++){
		for (var x=0; x<gradientshadow.depth; x++){
  		var shadowdiv=document.getElementById("shadow"+i+"_"+x)
			shadowdiv.style.width = gradientshadow.containers[i].offsetWidth + "px"
			shadowdiv.style.height = gradientshadow.containers[i].offsetHeight + "px"
			shadowdiv.style.left = gradientshadow.containers[i].offsetLeft + x + "px"
			shadowdiv.style.top = gradientshadow.containers[i].offsetTop + x + "px"
		}
	}
}
}

if (window.addEventListener)
window.addEventListener("load", gradientshadow.create, false)
else if (window.attachEvent)
window.attachEvent("onload", gradientshadow.create)
else if (document.getElementById)
window.onload=gradientshadow.create

function truncateStringWB(stringt,maxsize){
    var size=0;
    var retVal="";
    var parts=stringt.split(" ");
    for(var i=0;i<parts.length;i++){
        if(size + parts[i].length + 1<=maxsize){
            size+=parts[i].length + 1;
            retVal+= parts[i] + " ";
        }else{
            break;
        }
    }
    return retVal;
}
