var MAX = 9;
var debug = false;
var is_IE = navigator.userAgent.toLowerCase().indexOf("msie")>-1;
var iframeFixer;
var dialogArray = new Object();
var yahooInit = false;
var defaultTimesArray = new Array();
var defaultSetKeeperArray = new Array();
var accArray = new Array();
var alertBaseURL = "alert.do";
var dcounter = 0;
var whatIsShowing = null;
var lastIndex = null;
var requestSubmitted = false;
var comboArray = new Array();
var isAjaxSupported = null;
var execArray = new Array();

if (debug) alert("initializing ajax");

function testAjaxSupport() {

    if (isAjaxSupported == null) {
        var url = 'tiles.do';
        var options = {
            asynchronous: false,
            method: "get",
            onSuccess: function(response) {
                isAjaxSupported = true;
            },
            onFailure: function(response) {
                isAjaxSupported = false;
            }
        };
        new Ajax.Request(url,options);
    }
    return isAjaxSupported;
}

function loadPage(url, divId, initPage) {
    loadPage(url, divId, initPage, null);
}

function loadPage(url, divId, initPage, anchor) {
    loadPage(url, divId, initPage, null, null);
}

function loadPage(url, divId, initPage, anchor, fixerTimer) {    
    if(testAjaxSupport()) {
        stopRefresh();
        if(undefined != iframeFixer) {
            iframeFixer.pause();
        }
        if ( $(divId) == null ) 
            divId = "1";
        showMessage(divId, "<font color='#B0C4EE'><center><br><br><br>loading ... </center></font>");
        if(anchor != null) {
            window.location.hash=anchor;
            if(is_IE) {
                if($('ajaxnav') != null ) 
                    $('ajaxnav').setAttribute('src', 'location.jsp?hash=none');
                else
                    url = url + "&notitle=T";
            }
        }
        else {
            if(is_IE) {
                var windowlocator = new PageLocator("window.location.href", "#");
                $('ajaxnav').setAttribute('src', 'location.jsp?hash='+escape(url));
                window.location=windowlocator.makeNewLocation(url);
            }
        }

        var options = {
            method: "get",
            onSuccess: function(response) {
                    process(divId, response, null, initPage, true);
                    yahooInit = false;
                    if ( url.indexOf("resolveMenu") != -1 ) {
                        for ( i=0;i<10;i++) {
                            if ( $("dialog"+i) != null ) {
                                if ( !yahooInit){
                                    yahooInit = true;
                                    try {
                                    YAHOO.namespace("dialog.container");
                                    }catch(er){}
                                }
                                initDialogWindow(i,true);
                            }
                        }
                    } else {
                        loadLib(url,true);
                        var globalInd = 0;
                        var txt = response.responseText;
                        while ( globalInd != -1 ) {
                            var ind1 = txt.indexOf("setSchedTimes",globalInd);
                            if ( ind1 != -1 ) {
                                var ind2 = txt.indexOf(";",ind1);
                                eval(txt.substring(ind1,ind2+1));
                                globalInd = ind2 + 1;
                            } else {
                                globalInd = -1
                            }
                        }
                    }
                    if(anchor != null) {
                        window.location.hash=anchor;
                        window.scrollBy(0,-10);
                    }
                    if(fixerTimer!=null) {
                        fixerTimer.setTimeout("checkWhetherChanged", 750);
                    }
                    if(undefined != iframeFixer) {
                        iframeFixer.resume();
                    }
            },
            onFailure: function(response) {
                window.location = url;
            }
        };

        new Ajax.Request(url,options);

    }else {
        window.location = url;
    }
}

function loadDiv(url, divId) {
    loadDiv(url, divId, null, null);    
}

function loadDiv(url, divId, sWin) {
    loadDiv(url, divId, sWin, null);
}

function loadDiv(url, divId, sWin, loadingDiv) {    
    stopRefreshForTile(divId);

    if(loadingDiv != null && loadingDiv != undefined) {
        showMessage(loadingDiv, "<font color='#B0C4EE'><center>loading ...</center></font>")
    }

    var options = {
        method: "get",
        onSuccess: function(response) {
            yahooInit = false;
            loadLib(url,false);
            process(divId, response, sWin, false, true);                        
            if(sWin=='wn1') {
                initLayer1();
            }
            else if(sWin=='wn3') {
                initLayer2();
            }
            if (url.indexOf("zoom") != -1 && !(Prototype.Browser.IE7 || Prototype.Browser.IE || Prototype.Browser.IE6) ) {
                var fromSearch = url.indexOf("zoom")+5;
                var level = url.substring(fromSearch, url.indexOf("&",fromSearch));
                setZoomLevel(document,level);
            }
        },
        onFailure: function(response) {
            window.location = url.replace('viewContent','tiles');
        }
    };

    new Ajax.Request(url,options);
}

function autoRefreshTile(url, divId, frequency) {
    if (frequency > 0) {
    
        if (frequency < 60)
            frequency = 60;
        
        if (execArray[divId] == null) {
            execArray[divId] = new PeriodicalExecuter(
                function(pe) {
                    refreshTile(url, divId);
                },
                frequency
            );
        }
    }
}

function refreshTile(url, divId) {

   if ( parent.isdebug ) { log('autoRefreshTile '+url,"refreshTile->sending")};
    
    var runEffect = (url.indexOf("type=1") != -1);
    
    var hcNode = $('hc'+divId);
    var hasHashCode = (hcNode!=null && hcNode.value!=null && hcNode.value!="");
    
    if(hasHashCode) {  
        url = url+'&hc='+hcNode.value;           
    }
    
    var options = {
        method: "get",
        onSuccess: function(response) {
            if(!hasHashCode || hcNode.value!=response.responseText){                
                process(divId, response, null, false, false, runEffect);
            }
        },
        onFailure: function(response) {
            //alert('Your browser does not support AJAX.  Please contact support.' + response.status+"  "+divId+"  "+url,"refreshTile");
        }
    };
    if ( parent.winArray ) {
        var index1 = url.indexOf("favId")+6;
        var index2 = url.indexOf("&",index1);
        if ( index2 == -1 )
            index2 = url.length
        var favId = url.substring(index1,index2);
        options = {
            method: "get",
            timeout: 30,  //30 sec timeout
            onSuccess: function(response) {
                parent.timeoutArray.set(favId,0);
                if(!hasHashCode || hcNode.value!=response.responseText){                
                    process(divId, response, null, false, false, runEffect);
                    log('autoRefreshTile '+url,"refreshTile->Updated");
                }
                else { 
                    log('autoRefreshTile '+url,"refreshTile->No Change");
                }
            },
            onFailure: function(response) {
                if ( response.status == 12029 ) {
                    log("Cannot connect to the internet","refresh tile");
                } 
                log('Your browser does not support AJAX.  Please contact support.' + response.status+"  "+divId+"  "+url,"refreshTile");
            },
            onTimeout: function() {
                log('autoRefreshTile '+url,"Timeout->"+favId+"->"+parent.timeoutArray.get(favId));
                if ( parent.timeoutArray.get(favId) == null ){
                    parent.timeoutArray.set(favId,0);
                }
                else
                    parent.timeoutArray.set(favId,parent.timeoutArray.get(favId)++);
                    
                if ( parent.timeoutArray.get(favId) > 0 ) {
                    var isAllWindowsTimedout = true;
                    parent.timeoutArray.keys.each( function(fid) {
                        if ( parent.timeoutArray.get(fid) == null || parent.timeoutArray.get(fid) == 0 ) {
                            isAllWindowsTimedout = false;
                        }
                    });
                    if ( isAllWindowsTimedout ) {
                        if ( confirm("Browser has stopped responding. Would you like to save the homepage layout before page reload?") ) {
                            parent.saveDesktop("SaveDesktop");
                        }
                        log(isAllWindowsTimedout,"isAllWindowsTimedout");
                        parent.window.location.reload(false);
                    }else {
                        log("Not all windows timedout","refresh");
                        parent.timeoutArray.set(favId,0);
                        parent.winArray[favId].setURL(parent.winArray[favId].getURL());
                    }
                }
            }
        };
    }
    new Ajax.Request(url,options);
}

function process(divId, response, sWin, initPage, startRefresh, runEffect) {
    var temp;
    try {
       if ("login"==response.getResponseHeader("title"))
            top.location.href="login.jsp";
    } catch(e) {;}

    try {
        temp =  response.getResponseHeader("Warning");
    }
    catch(e){}    
    if ( $(''+divId) == null)
        return;
    // only if there are no warnings
    if("'booted'" != temp) {        
        $(''+divId).innerHTML = response.responseText;                
        if (runEffect && !initPage && sWin == null){
            new Effect.Highlight(''+divId, { startcolor: '#CC3333',endcolor: '#ffffff', restorecolor: '#ffffff' });
         //   Effect.Pulsate(''+divId,{ pulses: 3, duration: 1 });
        }
        var reportArray = $$("#report");
        for ( i=0;i<reportArray.length;i++) {
            var report = reportArray[i].value;
            if ( $("filterInput"+report).innerHTML == "" ) {
                setQSParams(report,"2");
                initQS(report);
            }
        }

        if(sWin=='cur')
            scrollWin(sWin);
        if(initPage)
            initScrollLayers();
        if(startRefresh) {
            if (isNaN(divId)){
                newTimers(true);
            }
            else {
                startRefreshForTile(divId);
            }
        }
    }
    else {
        $('rootDiv').innerHTML = response.responseText;
    }
}


function initScrollLayers() {
    initLayer1();
    initLayer2();
}


function initLayer1() {
    if($('lyr1') != null) {
        var wndo1 = new dw_scrollObj('wn1', 'lyr1');
        wndo1.setUpScrollbar("dragBar1", "track1", "v", 1, 1);
    }
}

function initLayer2() {
    if($('lyr2') != null) {
        var wndo2 =  new dw_scrollObj('wn3', 'lyr2');
        wndo2.setUpScrollbar("dragBar2", "track2", "v", 1, 1);
    }
}

function showMessage(divId, text) {
   try {
         $(divId).innerHTML =  text;
    }catch(e) { if(debug) alert(divId);}
}

function scrollWin(sWin) {
    if(sWin!=null && sWin != undefined) {
        try {
            if(sWin!='cur') {
                dw_scrollObj.scrollTo(sWin,0,0);
            }
            else {
                window.scrollTo(0,0);
            }
        }catch(e) {if(debug) alert(e.message)}
    }
}

function newTimers(stopFirst) {
    if(stopFirst) 
        stopRefresh();

    for (iTile =  1; iTile <= MAX; iTile++) 
        startRefreshForTile(iTile);
}


function stopRefreshForTile(iTile) {        
    try {
        if (execArray[''+iTile] != null){
            if(debug) alert("stopRefreshForTile t"+iTile);
            execArray[''+iTile].stop();
            execArray[''+iTile] = null;
            
        }
    }catch(e) {if(debug) alert(e.message)}
}

function startRefreshForTile(iTile) {    
    stopRefreshForTile(iTile);
    try {    
        autoRefreshTile($("autoUrl"+iTile).value, iTile, $("autoRate"+iTile).value);        
    }catch(e) {if(debug) alert(e.message)}
}

function stopRefresh() {  
    if (execArray.length > 0) {
        for (iTile = 0;iTile < MAX; iTile++)
            stopRefreshForTile(iTile);    
        execArray = new Array();
    }    
}

function toggleRefresh(imgId, divId) {
    
    var on;
    var image =  $(imgId);

    if ( !image ) {
        stopRefreshForTile(divId);
        return;
    }

    switch (image.src.indexOf('stop.jpg')) {
    case -1:
        image.src =  "images/stop.jpg";
        image.alt =  "click to stop refreshing";
        on =  true;
        break;
    default:
        image.src =  "images/start_refresh.jpg";
        image.alt =  "click to start refreshing";
        on =  false;
        break;
    }

    if(on) {         
        autoRefreshTile($("autoUrl"+divId).value, divId, $("autoRate"+divId).value);        
    }
    else {
        stopRefreshForTile(divId);
    }
}

function changeClass(id, newClass) {
    var identity=$(id);
    if(identity!=null)
        identity.className=newClass;
}

function changeTab(url, divId, sWin, tabIndex, eclass) {
    loadDiv(url, divId, sWin, divId);

    if(tabIndex==1) {
        enableTab(1, eclass);
        disableTab(2);
        disableTab(3);
        disableTab(4);
    }
    else if(tabIndex==2) {
        enableTab(2, eclass);
        disableTab(1);
        disableTab(3);
        disableTab(4);
    }
    else if(tabIndex==3) {
        enableTab(3, eclass);
        disableTab(1);
        disableTab(2);
        disableTab(4);
    }
    else if(tabIndex==4) {
        enableTab(4, eclass);
        disableTab(1);
        disableTab(2);
        disableTab(3);
    }
}

function disableTab(tabIndex) {
    var tabName     =  "tab"+tabIndex;
    var toolbarName =  "toolbar"+tabIndex;
    var blockName   =  "block"+tabIndex;
    var titleName   =  "title"+tabIndex;

    var node =  $(toolbarName);
    if(node!=null) {
        node.hide();
        $(tabName).style.backgroundColor='#FFFFFF';
    }
    changeClass(blockName, 'title_disabled');
    changeClass(titleName, 'headerlink');
}


function enableTab(tabIndex, eclass) {
    var tabName     =  "tab"+tabIndex;
    var toolbarName =  "toolbar"+tabIndex;
    var blockName   =  "block"+tabIndex;
    var titleName   =  "title"+tabIndex;

    var node =  $(toolbarName);
    if(node!=null) {
        node.show();
        $(tabName).style.backgroundColor='#336699';
    }
    changeClass(blockName, eclass);
    changeClass(titleName, 'headerlink2');
}

//*************************    functions of quickDealSearch ***********************************//
function setQSParams(rep,id) {    
    stopRefreshForTile(id);
    comboArray[rep] = new dhtmlXCombo("filterInput"+rep,"filterInput"+rep,300);
}

function initQS(rep) {
    var db = rep;
    var cache = false;
    var autosubload = false;
    //comboArray[rep].setComboText("");
    comboArray[rep].clearAll(true);
    var manager = $("stype1"+rep).checked == true ? $("stype1"+rep).value : $("stype2"+rep).value;
    var contains = $("contains2"+rep).checked;
    if ( contains ) {
        cache = false;
        autosubload = false;
    }
    var url = "servlet/searchServlet?db="+db+"&manager="+manager+"&contains="+contains;
    comboArray[rep].enableFilteringMode(true,url,cache,autosubload);
    comboArray[rep].attachEvent("onKeyPressed",function(Gb){
        if ( Gb == 13 ) {
            comboArray[rep].openSelect();
            window.setTimeout(function(){
                comboArray[rep].selectOption(0,true,true);
                comboArray[rep].closeAll();
            },2000);
        } else {
            if (this._mytimer) window.clearTimeout(this._mytimer);
             this._mytimer = window.setTimeout(function(){
                if ( comboArray[rep].getComboText() != "" && comboArray[rep].optionsArr.length == 0 ) {
                    alert("No Data Found");
                }
            },2000);
        }
    });
    comboArray[rep].attachEvent("onOpen",function(){
        window.setTimeout(function(){  },1000);
    });
}

function runReport(report, permission){
    try{
        if ( permission == "false" ) {
            notPermitted();
            return;
        }
        var id = comboArray[report].getSelectedValue();
        if ( id == null ) {
            //Do not pick first option just return
            //comboArray[report].selectOption(0,true,true);
            //id = comboArray[report].getSelectedValue();
            return;
        }
        var iType = $("stype1"+report).checked == true ? 1 : 2;
        var rootURL = $("rootURL"+report).value;
        var runid = id.replace(/&/g,"amp;").replace(/,/,"\,");

        comboArray[report].DOMelem_input.blur();

        var reportURL = rootURL + "/igmrpt/reports.runquickreport?p_rep_id=CW_US&";
        if (report != null && report != undefined)
          reportURL = rootURL + "/igmrpt/reports.runquickreport?p_rep_id="+report+"&";

        if (iType == 1)
          reportURL += "issuer_id="+ runid + "&bookrunner_id=&";
        else
          reportURL += "issuer_id=&bookrunner_id=" + runid + "&";

        reportURL += "p_username="+$("userId"+report).value;
        reportURL += "&p_sid="+$("sessionId"+report).value;

        var winId = id.replace(/ /g,"_")+iType;
        winId = winId.replace(/;/g,"and").replace(/&/g,"amp");
        winId = winId.replace(/,/g,"com");
        var w = 1000; //screen.availWidth/1.125;
        var h = 700; //screen.availHeight/1.125;
        openWin(reportURL,winId,w,h,'fullscreen=no,toolbar=yes,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,channelmode=no,directories=no');
        return false;
    }catch(excep){}
  }

function inpfocus(rep){
    if ( window.event.srcElement.id.indexOf("submit") == -1 ) {
        comboArray[rep].DOMelem_input.focus();
    }
}

// ************************** Alert Functions ***************************/

function notPermitted(event){
    $("npdiv").style.display="block";
    var options = {
        method: "get",
        contentType: "text",
        onSuccess: function(response) {
            $("npcontent").innerHTML = '<div style="width: 920px;height: 480px;overflow:auto;">' + response.responseText + '</div>';
        },
        onFailure: function(response) {
            alert("Failed to get not permitted page");
        }
    };
    new Ajax.Request("files/home/igm_contact.htm",options);
}

function getIndex(index){
    var defsetId = index;
    if (isNaN(index)) {
        for (iTile = 0;iTile < defaultSetKeeperArray.length; iTile++) {
            if (defaultSetKeeperArray[iTile] != undefined) {
                var alertObj = defaultSetKeeperArray[iTile];
                if (alertObj.tileId == index){
                    defsetId = iTile;
                    break;
                }
            }
        }
    }
    return defsetId;
}

function getAlertStatus(){

    for (iTile = 0;iTile < defaultSetKeeperArray.length; iTile++) {
            if (defaultSetKeeperArray[iTile] != undefined && $("alertStatus"+defaultSetKeeperArray[iTile].tileId)) {
                return $("alertStatus"+defaultSetKeeperArray[iTile].tileId).value
            }
    }
    return "Enabled";
}

function initEmail() {
	try{
            if (YAHOO.dialog.container.manager == null)
                YAHOO.dialog.container.manager = new YAHOO.widget.OverlayManager();
            var index = this.data;
            var defsetId = getIndex(index);

            var isReset = true;
            var defaultStartTime = null;
            var defaultEndTime = null;
            var defaultType = "";
            // Define various event handlers for Dialog
            var handleSubmit = function() {
                if ( $("alertNumber") != null && parseInt(dcounter)  == 0) {
                   dcounter =  $("alertNumber").value;
                } else if ( $("alertNumber") == null ) {
                    dcounter = 0;
                    for ( var t in dialogArray ){
                        var i = getIndex(t)
                        if ( $("show"+t) != null && defaultSetKeeperArray[i] != null){
                            dcounter++;
                        }
                    }
                }
                if ( parseInt(dcounter) >= 20 ) {
                    alert("You are not allowed to create more than 20 alerts");
                    return;
                }
                isLiveChecked = false;
                isSchedChecked = false;
                if ( $("mailtype"+index+""+1) != null )
                    isLiveChecked = $("mailtype"+index+""+1).checked;
                //alert(isLiveChecked);
                if ( $("mailtype"+index+""+2)!=null )
                    isSchedChecked = $("mailtype"+index+""+2).checked;
                //log(isSchedChecked);
                if ( !isLiveChecked && !isSchedChecked ) {
                    handleUnsubscribe(this);
                    return;
                }

                YAHOO.util.Event.removeListener("show"+index, "click");
                alertURL = alertBaseURL +  "?";
                defaultTimesArray["temp"] = new Array();
                var length = eval("document.dialogForm"+index+".elements").length-2;
                for ( k=0;k<length;k++){
                    var elem = eval("document.dialogForm"+index+".elements[k]");
                    if ( elem.checked == undefined ) {
                        alertURL+=elem.id+"="+elem.value+"&";
                        if ( elem.id.indexOf("starttime") != -1 ) {
                            defaultStartTime = elem.value;
                        } else if ( elem.id.indexOf("endtime") != -1 ) {
                            defaultEndTime = elem.value;
                        }
                    } else if ( elem.checked ) {
                        alertURL+=elem.id+"="+elem.value+"&";
                        if ( elem.value == "allday" ) {
                            defaultType = "L";
                        } else if ( elem.value == "hours" ) {
                            defaultType = "P";
                        } else if ( elem.value == "scheduled" ) {
                            defaultType = "S";
                        } else if ( elem.id.indexOf("sched") != -1 ) {
                            defaultTimesArray["temp"][defaultTimesArray["temp"].length] = new defaultTimes(defaultTimesArray["temp"].length,elem.value,index);
                        }
                    } else if ( elem.type == "hidden" ) {
                        alertURL+=elem.id+"="+encodeURI(elem.value) + "&";
                    }
                }

                if ( defaultTimesArray["temp"].length == 0 && defaultType == "S") {
                    alert("No time is selected");
                    return;
                }
                //var tempDefault = new defaultSet(index,defaultStartTime,defaultEndTime,defaultType);
                //setDefault(defaultType,defaultStartTime,defaultEndTime,index);
                var defsetId = getIndex(index);
                var submit_options = {
                    method: "get",
                    contentType: "text",
                    onSuccess: function(response) {
                        if ( comboArray["zAlert"] != null && defaultSetKeeperArray[defsetId].type == "" ) {
                            reloadAlertTable(true,null,index);
                            if ( $("alert_ID"+index) == null ) {
                                $("alert_ID"+index).parent.removeChild($("alert_ID"+index));
                                getElementById("alert_Title"+index).parent.removeChild(getElementById("alert_Title"+index));
                            }
                            createHiddenElement(window.document.body,"starttime"+index,defaultStartTime);
                            createHiddenElement(window.document.body,"endtime"+index,defaultEndTime);
                            createHiddenElement(window.document.body,"type"+index,defaultType);
                            createHiddenElement(window.document.body,"alert_ID"+index,index);
                            createHiddenElement(window.document.body,"alert_Title"+index,$("alert_Title"+index).value);

                            var tmpStatus = getAlertStatus();
                            createHiddenElement(window.document.body,"alertStatus"+index,tmpStatus);
                        } else {
                            $("type"+index).value = defaultType;
                            if ( defaultSetKeeperArray[defsetId].type == "") {
                                dcounter++;
                            }
                        }
                        setDefault(defaultType,defaultStartTime,defaultEndTime,index);
                        changeIcon(index,"subscribed");
                        defaultTimesArray[index] = defaultTimesArray["temp"];
                        defaultTimesArray["temp"] = null;
                        YAHOO.util.Event.addListener("show"+index, "click", show, dialogArray[index], true);
                    },
                    onFailure: function(response) {
                        alert("Failed to submit");
                        defaultTimesArray["temp"] = null;
                    }
                };
                new Ajax.Request(alertURL,submit_options);
                isReset = false;
                this.cancel();
            };

            var handleSuspend = function(obj) {

                alertURL = alertBaseURL + "?suspendAlerts=true?alert_ID="+$("alert_ID"+index).value;
                var suspend_options = {
                    method: "get",
                    contentType: "text",
                    onSuccess: function(response) {
                       var newStatus = "Enabled";
                        if ($("alertStatus"+index) && $("alertStatus"+index).value != "Suspended"){
                            newStatus = "Suspended";
                        }

                        for (iTile = 0;iTile < defaultSetKeeperArray.length; iTile++) {
                            if (defaultSetKeeperArray[iTile] != undefined) {
                                var alertObj = defaultSetKeeperArray[iTile];
                                if ($("alertStatus"+alertObj.tileId)) {
                                    $("alertStatus"+alertObj.tileId).value = newStatus;
                                    if ($("type"+alertObj.tileId))
                                        changeIcon(alertObj.tileId,$("type"+alertObj.tileId).value);
                                }
                            }
                        }
                        var onAddTileId = comboArray["zAlert"].getSelectedValue();
                        $("alertStatus"+onAddTileId).value = newStatus;
                    },
                    onFailure: function(response) {
                        alert("Failed to suspend");
                        alert(response.responseText);
                    }
                };
                new Ajax.Request(alertURL,suspend_options);
                try{
                    obj.cancel();
                }catch(oi) {
                    this.cancel();
                }
	};

            var handleUnsubscribe = function(obj) {
                var selectedOption = getSelectedOption(index);
                if ( selectedOption != null ) {
                    selectedOption.checked = false;
                }
                alertURL = alertBaseURL + "?alert_ID="+$("alert_ID"+index).value;
                var unsubscribe_options = {
                    method: "get",
                    contentType: "text",
                    onSuccess: function(response) {
                        if ( comboArray["zAlert"] != null ) {
                            reloadAlertTable(false,$("alert_Title"+index).value,$("alert_ID"+index).value);
                            resetDefault("starttime"+index,$("defaultStartTime").value);
                            resetDefault("endtime"+index,$("defaultEndTime").value);
                            resetDefault("type"+index,"");
                        } else {
                            changeIcon(index,"");
                        }
                        dcounter--;
                        defaultSetKeeperArray.splice(getIndex(index),1);
                        delete defaultTimesArray[getIndex(index)];
                        clearSchedTimes(index);
                        try {
                            eval("document.dialogForm"+index+".livetype"+index+"[0].checked=false");
                            eval("document.dialogForm"+index+".livetype"+index+"[1].checked=false");
                        }catch(exc){}
                    },
                    onFailure: function(response) {
                        alert("Failed to unsubsribe");
                        alert(response.responseText);
                    }
                };
                new Ajax.Request(alertURL,unsubscribe_options);
                try{
                    obj.cancel();
                }catch(oi) {
                    this.cancel();
                }
	};

	var handleSuccess = function(o) {
		var response = o.responseText;
		response = response.split("<!")[0];
		$("resp").innerHTML = response;
	};

	var handleFailure = function(o) {
		alert("Submission failed: " + o.status);
	};

        var onDialogClose = function(type,args, me){
            try {
                if ( isReset ) {
                    reset(index);
                } else {
                    isReset = true;
                }
                if ( comboArray["zAlert"] != null ) {
                    whatIsShowing = null;
                    if ( index != comboArray["zAlert"].getActualValue() )
                        lastIndex = index;
                    else
                        lastIndex = null;
                    clearLiveType(index);
                    clearSchedTimes(index);
                } else {
                    window.setTimeout("refreshIt("+index+")",100);
                    window.setTimeout("refreshIt("+index+")",200);
                }
            }catch(rt) {alert(tr.message);}
        }

        var onDialogOpen = function(type,args,me){
            if ( $("row"+index) != null ) {
                if ( lastIndex != null )
                    $("row"+lastIndex).getElementsByTagName("td")[1].style.backgroundColor = "#F4F4F4";
                $("row"+index).getElementsByTagName("td")[1].style.backgroundColor = "#f9f7ba";
            } else if ( comboArray["zAlert"] != null && index == comboArray["zAlert"].getActualValue() && lastIndex != null ){
                $("row"+lastIndex).getElementsByTagName("td")[1].style.backgroundColor = "#F4F4F4";
            }

        }

        if ( this.isPage ||  dialogArray[index] == null) {
            if ( dialogArray[index] != null ) {
                YAHOO.dialog.container.manager.remove([dialogArray[index]]);
            }
             var fxc = true;
            // log("za="+$("unselectedAlerts")+":"+comboArray["zAlert"]);
             if ( $("unselectedAlerts") != null || comboArray["zAlert"] != null ) {
                fxc = false;
            }

            dialogArray[index] = new YAHOO.widget.Dialog("dialog"+index,
                                                            { width : "300px",
                                                              xy:[500,0],
                                                              fixedcenter : fxc,
                                                              visible : false,
                                                              constraintoviewport : true,
                                                              buttons : [ { text:"Stop/Resume All", handler:handleSuspend },
                                                                          { text:"Save", handler:handleSubmit, isDefault:true },
                                                                          { text:"Unsubscribe", handler:handleUnsubscribe }
                                                                          ]
                                                            });

            YAHOO.dialog.container.manager.register([dialogArray[index]]);
            dialogArray[index].hideEvent.subscribe(onDialogClose,this);
            dialogArray[index].showEvent.subscribe(onDialogOpen,this);
            // Render the Dialog
            dialogArray[index].render();

            if ( $("show"+index) != null ) {
                YAHOO.util.Event.addListener("show"+index, "click", show, dialogArray[index], true);
            } else if ( comboArray["zAlert"] != null && index == comboArray["zAlert"].getSelectedValue() ){
                YAHOO.util.Event.removeListener("addAlert", "click");
                YAHOO.util.Event.addListener("addAlert", "click", show, dialogArray[index], true);
            }
            $(dialogArray[index].id).style.display="none";
        }
        if (alertBeanArray.length == 0 || alertBeanArray[alertBeanArray.length-1] == index ) {        
            $("myal").style.visibility="visible";
            $("splash").style.display="none";
        }
        
    }catch(e){
        log(e.message,"initEnail");
    }
}
function createHiddenElement(parent,id,value){
     if ( $(id) == null ) {
         var alertInp = document.createElement("input");
         alertInp.type = "hidden";
         alertInp.id = id;
         alertInp.value = value;
         alertInp.style.display="none";
         parent.appendChild(alertInp);
     }
 }

function refreshIt(index){
    try{
        var cmd = unescape($("refreshLink"+index).href);  
        eval(cmd.substring(11));
    }catch(excep){
       log(excep.message,"refreshIt");
    }
}

function show(e, obj){
    try{
        if ( whatIsShowing != null && comboArray["zAlert"] != null ) {
            whatIsShowing.hide();
        }
        $(obj.id).show();
        obj.show();
        setDelayedDefault(obj.id.substring(6));
        if ( comboArray["zAlert"] == null )
            stopRefreshForTile(obj.id.substring(6));
        whatIsShowing = obj;
    }catch(t){alert("show"+t.message);}
}

function getSelectedOption(index) {
    for ( i=1;i<3;i++) {
        tid = "mailtype"+index+""+i;
        if ( $(tid) != null &&  $(tid).checked ) {
            return $(tid);
        }
    }
    return null;
}

function resetDefault(id,value){
    if ( $(id) != null ) {
        $(id).value = value;
    }
}

function reloadAlertTable(add,text,value) {
    var table = $("alertsTable");
    var rows = table.getElementsByTagName("tr");
    if ( add ) {

        var tileId = comboArray["zAlert"].getSelectedValue();
        var row = table.insertRow(table.rows.length);
        row.valign = "middle";
        row.id = "row" + value;
        var td = row.insertCell(0);
        var newText = "<div align=\"right\"><img src=\"images/email.gif\" id='show" + tileId + "' alt=\"Alert\" width=\"17\" height=\"14\" border=\"0\" style=\"cursor:pointer;cursor:pointer;\"/></div>";
        td.innerHTML = newText;
        row.appendChild(td);
        td = row.insertCell(1);
        newText = "<div style='COLOR: #000000;font-family: Verdana;font-size: 10pt;'>"+comboArray["zAlert"].getComboText()+"</div>";
        td.innerHTML = newText;
        comboArray["zAlert"].deleteOption(tileId);
        comboArray["zAlert"].loadXML("jsonServlet?parent="+comboArray["zProduct"].getActualValue(), function(){
            if ( comboArray["zAlert"].optionsArr.length > 0 ) {
                window.setTimeout(onAdd,700);
            } else {
                comboArray["zAlert"].setComboText("");
                $("addAlert").style.visibility = "hidden";
            }
            });
    } else {
            for ( t=0;t<rows.length;t++){
                if ( rows[t].id == "row"+value ) {
                    table.deleteRow(t);
                    var divForm = $("dialogFormDiv"+value);
                    if ( divForm != null ) {
                        divForm.parentNode.removeChild(divForm);
                    }
                    dialogArray[value] = null;
                }
            }
            comboArray["zAlert"].loadXML("jsonServlet?parent="+comboArray["zProduct"].getActualValue(),onAdd);
            comboArray["zAlert"].selectOption(0,false,false);
    }

}

function checkMailTypeBack(obj,check) {
    check.checked=true;
    realId = check.id.substring(0,check.id.length-1);
    id = 2;
    if ( $(realId+id)!= null )
        $(realId+id).checked = false;
    if ( obj.value == "allday" ) {
        setDefaultTime(obj.id.substring(8,obj.id.length));
    }
}

function checkMailType(check) {
    realId = check.id.substring(0,check.id.length-1);
    tileId = check.id.substring(8,check.id.length-1);
    id = check.id.substring(check.id.length-1,check.id.length) == "1" ? "2" : "1";
    if ( check.checked ) {
        if ( $(realId+id) != null ) {
            $(realId+id).checked = false;
        }
        if ( id == "2" ) {
            // set default livetype option
            eval("document.dialogForm"+tileId+".livetype"+tileId+"[0].checked=true");
        }
        uncheckOptions(id,tileId);
    } else {
        uncheckOptions(check.id.substring(check.id.length-1,check.id.length),tileId);
    }
}

function uncheckOptions(id,tileId){
    if ( id == 1 ) {
        clearLiveType(tileId);
        setDefaultTime(tileId);
    } else if ( id == 2 ) {
        clearSchedTimes(tileId);
    }
}

function setDefaultTime(id){
    if ($("starttime"+id) != null ) {
        $("starttime"+id).value = $("defaultStartTime").value;
        $("starttimeConv"+id).innerHTML = showLocalTime($("starttime"+id).value);
        $("endtime"+id).value = $("defaultEndTime").value;
        $("endtimeConv"+id).innerHTML = showLocalTime($("endtime"+id).value);
    }
}

function validateTime(select,tileId){//Not really validates but just default set
    eval("document.dialogForm"+tileId+".livetype"+tileId+"[1].checked=true");
    eval("document.dialogForm"+tileId+".livetype"+tileId+"[1].click();");
    $(select.id.substring(0,select.id.indexOf("time")+4)+"Conv"+tileId).innerHTML = showLocalTime(select.value);
}

function loadLib(url,isPage){

    if ( !testAjaxSupport() )
        return;
    else if ( $("unselectedAlerts") != null ) {
        initmyalert();
    }
    var tempFlag = yahooInit;
    try{
        if ( !yahooInit){
            yahooInit = true;
            YAHOO.namespace("dialog.container");
        }
        ind = url.indexOf("tileid=");
        var tileId;
        if ( ind == -1 ){
            //looking for dalogs to get the tile
            var divArray = $$("div");
            for ( t=0;t<divArray.length;t++){
                if ( divArray[t].id.substring(0,6) == "dialog") {
                    tileId = divArray[t].id.substring(6);
                    if ($("type"+tileId) != null ) {
                        initDialogWindow(tileId,isPage);
                    }
                } else if ( divArray[t].id == "alertRequest" ) {
                     tileId = divArray[t].tl;
                      (function() {
                        YAHOO.util.Event.onContentReady("submitEnable"+tileId,
                        function() {var q1 = new YAHOO.widget.Button("submitEnable"+tileId, { onclick: { fn: onButtonClick1 } });
                           q1 = YAHOO.util.Dom.addClass("submitEnable"+tileId, "default-button");
                            function onButtonClick1(p_oEvent) {
                              submitRequest();
                            }
                            })
                          YAHOO.util.Event.onContentReady("cancelEnable"+tileId,
                          function() {var q2 = new YAHOO.widget.Button("cancelEnable"+tileId, { onclick: { fn: onButtonClick2 } });
                              q2 = YAHOO.util.Dom.addClass("cancelEnable"+tileId, "default-button");
                             function onButtonClick2(p_oEvent) {
                              closeAlertRequest();
                             }
                          })
                         })();
                         break;
                }
             }
            var spanArray = $$("span");
            for ( z=0;z<spanArray.length;z++) {
                if ( spanArray[z].id.indexOf("localTime") != -1 ) {
                    var tm = spanArray[z].id.substring(9,14);
                    spanArray[z].innerHTML = showLocalTime(tm);
                }
            }
        } else {
            tileId = url.substring(ind+7,url.length);
            tempIndex = tileId.indexOf("&");
            if ( tempIndex != -1 ) {
                tileId = tileId.substring(0,tempIndex);
            }
            initDialogWindow(tileId,isPage);

        }
    }catch(y){alert("loadLib "+y.message);}
}

function initDialogWindow(tileId,isPage){
    if ( $("accordion"+tileId) != null ) {
            eval("acc"+tileId+"=new Accordion('accordion"+tileId+"','h3','acc"+tileId+"')");
            if ( eval("acc"+tileId+".length") == 3 ) {
                    window.setTimeout("acc"+tileId+".show(1, false,'accordion"+tileId+"')",2500);
            }
            YAHOO.util.Event.onDOMReady(initEmail,{data:tileId,isPage:isPage},true);
            YAHOO.util.Event.removeListener("b_submit"+tileId, "click");
            YAHOO.util.Event.onContentReady("b_submit"+tileId,
               function() {var q = new YAHOO.widget.Button("b_submit"+tileId, { onclick: { fn: onButtonClick } });
               q = YAHOO.util.Dom.addClass("b_submit"+tileId, "default-button");
               function onButtonClick(p_oEvent) {
                    sendFriendEmail(tileId);
                }
             });
            if ( $("type"+tileId) != null ) {
                if ( $("starttime"+tileId) != null ) {
                    if ( defaultSetKeeperArray[tileId] == null || isPage ) {
                        setDefault($("type"+tileId).value,$("starttime"+tileId).value,$("endtime"+tileId).value,tileId);
                    }
                    else {
                        setDefault(defaultSetKeeperArray[tileId].type,defaultSetKeeperArray[tileId].starttime,defaultSetKeeperArray[tileId].endtime,tileId);
                    }
                } else
                    setDefault(( (defaultSetKeeperArray[tileId] == null || isPage) ? $("type"+tileId).value : defaultSetKeeperArray[tileId].type),$("starttime"+tileId),$("endtime"+tileId),tileId);
            }
        }
}

function setDefault(type,start_time,end_time,tileId){
    if (isNaN(tileId)) {
        if ( getIndex(tileId) == tileId )
            defaultSetKeeperArray[defaultSetKeeperArray.length] = new defaultSet(tileId,start_time,end_time,type);
        else
            defaultSetKeeperArray[getIndex(tileId)] = new defaultSet(tileId,start_time,end_time,type);
    }
    else{
        defaultSetKeeperArray[tileId] = new defaultSet(tileId,start_time,end_time,type);
    }
    changeIcon(tileId,type);
    if ( $("starttimeConv"+tileId) != null ) {
        $("starttimeConv"+tileId).innerHTML = showLocalTime($("starttime"+tileId).value);
        $("endtimeConv"+tileId).innerHTML = showLocalTime($("endtime"+tileId).value);
    }
}

function setDelayedDefault(id){

    try{
        var defsetId = getIndex(id);
        if ( defaultSetKeeperArray[defsetId] == null ) {
            //default was not set
            setDefault("",$("defaultStartTime").value,$("defaultEndTime").value,id);
            defsetId = defaultSetKeeperArray.length - 1;
        }

        var defset = defaultSetKeeperArray[defsetId];
        arg = defset.type == "S" ? id+""+2 : id+""+1;
        if ( defset.type == "L" ) {
            $("mailtype"+arg).click();
            $("mailtype"+arg).checked = true;
            eval("document.dialogForm"+id+".livetype"+id+"[0].click()");
        }else if ( defset.type == "P" ) {
            $("mailtype"+arg).click();
            $("mailtype"+arg).checked = true;
            eval("document.dialogForm"+id+".livetype"+id+"[1].click()");
            $("starttime"+id).value = defset.starttime;
            $("endtime"+id).value = defset.endtime;
        } else if ( defset.type == "S" ) {
            $("mailtype"+arg).click();
            $("mailtype"+arg).checked = true;
            setDelayedSchedTimes(id);
        } else if ( defset.type == "" ) {
            if ( $("mailtype"+id+""+1) != null ) {
                $("mailtype"+id+""+1).checked = false;
            }
            if ( $("mailtype"+id+""+2) != null )
                $("mailtype"+id+""+2).checked = false;
            }
            if ( $("starttimeConv"+id) != null ) {
                $("starttimeConv"+id).innerHTML = showLocalTime($("starttime"+id).value);
                $("endtimeConv"+id).innerHTML = showLocalTime($("endtime"+id).value);
            }
    }catch(e) {
        alert("setDelayedDefault "+e.message);
    }
}

function changeIcon(tileId,type) {
    
    if ( $("show"+tileId) == null )
        return;    
    
    if ( type != "" ) {
        if ($("alertStatus"+tileId) != null && $("alertStatus"+tileId).value == "Suspended")
            $("show"+tileId).src="images/email_suspended.gif";
        else
            $("show"+tileId).src="images/email_subscribed.gif";
    } else {
        $("show"+tileId).src="images/email.gif";
    }
}

function setSchedTimes(time,tileId){
    if ( defaultTimesArray[tileId] == null ) {
        defaultTimesArray[tileId] = new Array();
    }
    defaultTimesArray[tileId][defaultTimesArray[tileId].length] = new defaultTimes(defaultTimesArray[tileId].length,time,tileId);
}

function setDelayedSchedTimes(tileId){
    try {
        var defsched = defaultTimesArray[tileId];
        if ( defsched == null ) {
            return;
        }
        for ( i=0;i<defsched.length;i++){
            if ( defsched[i] != null ) {
                $("sched"+defsched[i].tileId+defsched[i].time).checked = true;
            }
        }
    }catch(excep){}
}

function selectScheduled(check,tileId){
    if ( check.checked ) {
        try {
        $("mailtype"+tileId+"2").checked=true;
        $("mailtype"+tileId+"1").checked=false;
        eval("document.dialogForm"+tileId+".livetype"+tileId+"[0].checked=false");
        eval("document.dialogForm"+tileId+".livetype"+tileId+"[1].checked=false");
        }catch(excep){}
    }
}

function defaultSet(tileId,starttime,endtime,type) {
    this.tileId = tileId;
    this.starttime = starttime;
    this.endtime = endtime;
    this.type = type;
}

function defaultTimes(id,time,tileId){
    this.id = id;
    this.time = time;
    this.tileId = tileId;
}

function reset(index){
    try{
        if ( defaultSetKeeperArray[index] == null )
            return;
        setDelayedDefault(index);
        //clear out all scheduled time first
        clearLiveType(index);
        clearSchedTimes(index);
        setDelayedSchedTimes(index);
    }catch(u){alert("reset "+u.message);
    }
}

function clearLiveType(index){
    var length = eval("document.dialogForm"+index+".elements").length-2;
    for ( k=0;k<length;k++){
        var elem = eval("document.dialogForm"+index+".elements[k]");
        if ( elem.id.substring(0,8) == "livetype" ) {
            elem.checked=false;
        }
    }
}

function clearSchedTimes(index){
    try {
        var length = eval("document.dialogForm"+index+".elements").length-2;
        for ( k=0;k<length;k++){
            var elem = eval("document.dialogForm"+index+".elements[k]");
            if ( elem.id.substring(0,5) == "sched" ) {
                elem.checked=false;
            }
        }
    }catch(excep){}
}

function showAlertRequest(tileId){
    $("alertRequest").style.display="inline";
    requestSubmitted = false;
}

function closeAlertRequest(){
    $("email2").value="";
    $("alertRequest").hide();
}

function submitRequest(){
    if ( requestSubmitted ) {
        return;
    }

    if ( $("city").value == "" ) {
        alert("City field cannot be empty");
        return;
    }
    if ( $("email1").value != $("email2").value ) {
        alert("Emails do not match. Please check your spelling.");
        return;
    }

    requestSubmitted = true;
    $("alertRequest").style.display="none";
    alertURL = alertBaseURL + "?enable=true&email="+$("email1").value+"&city="+$("city").value;
    var options = {
        method: "get",
        contentType: "text",
        onSuccess: function(response) {
             $("alertRequest").style.display="none";
        },
        onFailure: function(response) {
            alert("Failed to submit request: "+response.responseText);
        }
    };
    new Ajax.Request(alertURL,options);
}

function sendFriendEmail(tileId) {
        toName = $("friendname"+tileId).value;
        if ( toName == "" ) {
            alert("Name cannot be blank!");
            return;
        }
        toEmail = $("friendemail"+tileId).value;
        if ( toEmail == "" ) {
            alert("Email cannot be blank!");
            return;
        }
        var toCompany = $("friendcompany"+tileId).value;
        if ( toCompany == "" ) {
            alert("Company cannot be blank!");
            return;
        }
        var toMessage = escape(encodeURI($("friendmessage"+tileId).value));
        alertId = $("alert_ID"+tileId).value;
        alertURL = alertBaseURL + "?submitEmail=true&toName="+toName+"&toEmail="+toEmail+"&alertId="+alertId+"&toCompany="+toCompany+"&toMessage="+toMessage;
        var options = {
            method: "get",
            onSuccess: function(response) {
                alert("Email has been sent.");
                $("friendname"+tileId).value = "";
                $("friendemail"+tileId).value = "";
                $("friendcompany"+tileId).value = "";
                $("friendmessage"+tileId).value = "";
            },
            onFailure: function(response) {
                alert("FAILED to send Email!");
            }
        };
        new Ajax.Request(alertURL,options);
        whatIsShowing.hide();
}

function initializeAddAlert(){

    alertURL = "tiles.do?page=myAlerts.do&nomenu=T&template=MyAlerts&add=true&alertId="+comboArray["zAlert"].getSelectedValue();

    var options = {
            method: "get",
            onSuccess: function(response) {
                tileId = comboArray["zAlert"].getSelectedValue();
                
                var placer = $("addPlacer");

                try{
                    
                    var placerDiv = $("addPlacer"+tileId);
                    if ( placerDiv != null && tileId != "") {
                        placerDiv.parentNode.removeChild(placerDiv);
                    }
                    var placerDiv = document.createElement("div");
                    placerDiv.id = "addPlacer"+tileId;
                    placer.appendChild(placerDiv);
                }catch(e){
                    alert("initialize add alert: "+e.message);
                }
                placerDiv.innerHTML = response.responseText;
                fromInd = 0;
                do {
                    indT = response.responseText.indexOf("localTime",fromInd);
                    if ( indT != -1 ) {
                        var time = response.responseText.substring(indT+9,indT+14);
                        $("localTime"+time+tileId).innerHTML = showLocalTime(time);
                        fromInd = indT + 25
                    }
                } while ( indT != -1 )
                startTime = $("defaultStartTime").value;
                endTime = $("defaultEndTime").value;
                $("addAlert").style.visibility = "visible";
                initDialogWindow(tileId,true);
            },
            onFailure: function(response) {
                alert("FAILED to initialize add alert "+response.responseText);
            }
        };
        new Ajax.Request(alertURL,options);
}

function onAdd(){
    if ( $("addAlert") == null )
        return;
    if ( comboArray["zAlert"].getSelectedText() == "" )
        comboArray["zAlert"].selectOption(0,false,false);
    comboArray["zAlert"].setComboText(comboArray["zAlert"].getSelectedText()); // to unselect
    $("addAlert").style.visibility = "hidden";
    YAHOO.util.Event.removeListener("addAlert", "click");
    initializeAddAlert();
}

function initD() {    
    for ( i=0; i < alertBeanArray.length; i++) {
        initDialogWindow(alertBeanArray[i],true);
    }
}

function initmyalert() {
    try {
        comboArray["zProduct"] = new dhtmlXComboFromSelect("products");
        comboArray["zAlert"] = new dhtmlXComboFromSelect("unselectedAlerts");
        comboArray["zProduct"].readonly(true);
        comboArray["zAlert"].readonly(true);
        comboArray["zProduct"].attachEvent("onChange",function(){                
            comboArray["zAlert"].loadXML("jsonServlet?parent="+comboArray["zProduct"].getActualValue(),onmyalertload);
        });
        comboArray["zAlert"].attachEvent("onChange",function(){
            onAdd();
        });
        onmyalertload();
    } catch (e) {
        alert("failed initmyalert "+e.message);
    }
}

function onmyalertload(){    
    if ( comboArray["zAlert"].optionsArr.length == 0 ) {
        comboArray["zAlert"].setComboText("");
        $("addAlert").style.visibility = "hidden";
    } else {
        replaceSC(comboArray["zAlert"]);
        comboArray["zAlert"].selectOption(0,true,true);
        window.focus();
    }
    initializeAddAlert();
    replaceSC(comboArray["zAlert"]);
}

function replaceSC(combo){
    for ( i=0;i<combo.optionsArr.length;i++) {
            if (combo.optionsArr[i].text.indexOf("amp;") != -1){
                var value = combo.optionsArr[i].value;
                combo.updateOption(value,value,combo.optionsArr[i].text.replace(/amp;/g,""));
            }
    }
}


//create movable dialog
var clicked = false;
var x;
var y;
var element;
var Xoffset;
var Yoffset;
reg = new RegExp("([0-9]*)px", "i");

function mouseDown(event, ele_name) {
    clicked = true;
    element = ele_name;
            if(event.clientX || event.clientY) {
                    clickX=event.clientX;
                    clickY=event.clientY;
            }
            else {
                    clickX=event.pageX;
                    clickY=event.pageY;
            }
    itemX = $(element).style.left;
    itemY = $(element).style.top;
    arX = reg.exec(itemX);
    arY = reg.exec(itemY);
    Xoffset = clickX - arX[1];
    Yoffset = clickY - arY[1];
    try{
        $('xoffsetval').innerHTML = Xoffset;
        $('yoffsetval').innerHTML = Yoffset;
        $('ytopval').innerHTML = $(element).style.top;
        $('xtopval').innerHTML = $(element).style.left;
    }catch(e){}
    $(element).style.cursor = 'move';
}

function movers(event) {
	if(clicked == true) {
	if(event.clientX || event.clientY) {
		x=event.clientX - Xoffset;
		y=event.clientY - Yoffset;
	}
	else {
		x=event.pageX - Xoffset;
		y=event.pageY -Yoffset;
	}
	$(element).style.top = y +'px';
	$(element).style.left = x +'px';
	}
}

function unclicks() {
    clicked = false;
    $(element).style.top = y +'px';
    $(element).style.left = x +'px';
    $(element).style.cursor = 'auto';
}

function showLocalTime(timeStr){
    var gmtTime = new Date();
    var timezone = gmtTime.getTimezoneOffset();
    var timeArray = timeStr.split(":");
    gmtTime.setHours(timeArray[0],timeArray[1]);
    var localTime = new Date();
    localTime.setTime(gmtTime.getTime() - timezone*60*1000);
    var hours = localTime.getHours().toString().length == 1 ? "0" + localTime.getHours() : localTime.getHours();
    var minutes = localTime.getMinutes().toString().length == 1 ? "0" + localTime.getMinutes() : localTime.getMinutes();
    var sign = timezone > 0 ? "-" : "+";
    var offset = timezone > 0 ? timezone/60 : timezone/60*(-1);
    if ( offset != 0 )
        return (" " + hours + ":" + minutes + " ( GMT " + sign + " " + offset + " )");
    else
        return (" " + hours + ":" + minutes + " ( GMT )");
}

function isJavaEnabled() {
    var i_java = false;
    if (navigator.mimeTypes && navigator.mimeTypes.length)
    if (typeof(navigator.mimeTypes['application/x-java-vm']) != "undefined") {
        i_java = true;
    }
    if (navigator.plugins) {
        for (var i=0; i < navigator.plugins.length; i++) {
            if (navigator.plugins[i].name.indexOf("Java Plug-in") >= 0) {
                i_java = true;
                break;
            }
        }
    }
    i_java==navigator.javaEnabled();
    return i_java;
}


// kept in case it's being used in files from file server //
function GP_AdvOpenWindow(myURL, winTitle, features, w, h, wa, il, aoT, acT, bl, tr, trT, slT, pu) {
    openWin(myURL, winTitle, w, h, features);
}

function openWindow(myURL, winTitle){    
    var w = screen.availWidth*6/8;
    var h = screen.availHeight*6/8;
    openWin(myURL, winTitle, w, h, "toolbar=yes,location=no,status=no,menubar=yes,scrollbars=yes,resizable=yes")
}

function openWin(myURL, winTitle, w, h, features){

    if (winTitle == 'undefined')
        winTitle = 'informa global markets';

    var leftPos = (screen.availWidth - w) / 2;
    var topPos = (screen.availHeight - h) / 2;

    if( leftPos < 0 ) {
        leftPos = 0;
    }
    if( topPos < 0 ) {
        topPos = 0;
    }
    var newWindow = window.open(myURL, winTitle, features+",width=" + w + ",height=" + h + ",top=" + topPos + ",left=" + leftPos );
    
    try {
        newWindow.focus();
    }catch(er){}    
    
}

function changePage(url) {
  var rform = document.forms['refreshForm'];
  window.location = (rform == null) ? url : url+"&refstatus="+rform.btnReadRefresh.value;
}

function printMe(url, id, frameName) {

    var w = 805;
    var h = 450;
    var leftPos = (screen.availWidth - w) / 2;
    var topPos = (screen.availHeight - h) / 2;

    if (frameName=="Calendar"){
        w = 750;
        h = 650;
        topPos = (screen.availHeight - h) / 4
    }

    if( leftPos < 0 ) {
        leftPos = 0;
    }
    if( topPos < 0 ) {
        topPos = 0;
    }

    var urlNode = $('h'+id);
    if(urlNode!=null && urlNode.value!="") {
        url = urlNode.value;
    }
    else {
        var innerFrame = frames[frameName];
        if(innerFrame != undefined) {
            var indexform = innerFrame.document.forms['indexForm'];
            if(indexform!=undefined) {
                url = url + '&index='+indexform.index.value+'&dir='+indexform.dir.value;
            }
        }
    }
    var newWindow = window.open(url, 'Print', "toolbar=yes,location=no,status=no,menubar=no,scrollbars=yes,width=" + w + ",height=" + h + ",resizable=yes,top=" + topPos + ",left=" + leftPos );
    newWindow.focus();
}


function changeFrameTwo(urlIn) {    
    try {
        frames["two"].window.stopRefresh();
    }catch(er){}    
    frames["two"].window.location=urlIn;
}
function chart_link(indicator, country, type ) {
    if (type == "H")
        document[indicator+country+type].src='images/charticon_h_clicked.gif';
    else
        document[indicator+country+type].src='images/charticon_f_clicked.gif';
    var urlSt= 'chartViewAction.do?menuid=P2H&indicatorId='+indicator+'&countryId='+country+'&searchType='+type;
    openWin(urlSt,'pop3',600,400,'fullscreen=no,toolbar=yes,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,channelmode=no,directories=no')
}

function viewTranslationResult(storyId, favorite, orphanwindow){
    var tmpImg = $("img_"+storyId).src;

    var longId = "long_"+storyId;
    var shortId = "short_"+storyId;

    var longAlt = $(longId).alt;

    var isClosed = tmpImg.indexOf("resulttraditional.png") > 0 ? true : false;
    
    $("img_"+storyId).src = (isClosed == true ? "images/resultsimplified.png" : "images/resulttraditional.png");

    if (isClosed) {
        $(longId).show();
        if (longAlt != "loaded") {
            $(longId).innerHTML = "Loading...";
            $(longId).alt = "loaded";

            url = "viewStory.do?storyid="+ storyId + "&menuid=usestory&tabid=usestory&tileid=1&encoding=GB2312";

            if (favorite == "true")
                url += "&favorite=T";
            else if (orphanwindow != "false")
                url = url + "&focuswin=" + orphanwindow;
            new Ajax.Updater(longId, url, { method: 'get' });

        }
        $(shortId).hide();
    }
    else {
        $(shortId).show();
        $(longId).hide();
    }
}



function viewSearchResult(storyId, favorite, orphanwindow){
    var tmpImg = $("img_"+storyId).src;

    var longId = "long_"+storyId;
    var shortId = "short_"+storyId;

    var longAlt = $(longId).alt;

    var isClosed = tmpImg.indexOf("resultopen.png") > 0 ? true : false;

    $("img_"+storyId).src = (isClosed == true ? "images/resultclose.png" : "images/resultopen.png");

    if (isClosed) {
        $(longId).show();
        if (longAlt != "loaded") {
            $(longId).innerHTML = "Loading...";
            $(longId).alt = "loaded";

            url = "viewStory.do?storyid="+ storyId + "&menuid=usestory&tabid=usestory&tileid=1&title=Search Result";

            if (favorite == "true")
                url += "&favorite=T";
            else if (orphanwindow != "false")
                url = url + "&focuswin=" + orphanwindow;
            new Ajax.Updater(longId, url, { method: 'get' });

        }
        $(shortId).hide();
    }
    else {
        $(shortId).show();
        $(longId).hide();
    }

}



/*
* cookies
*/
function setCookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
        
  document.cookie = cookie_string;
}

function deleteCookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function getCookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );


  if ( results ) {
    return ( unescape ( results[2] ) );
  } else
    return null;
}
