/*************************************************
 * validations.js
 * Sreejith.P.S
 * 11.08.2008
 *
 * file used for validating the fields                                                                                                                                        
 *************************************************/   

/**
 * Sreejith.P.S
 * 11.08.08
 * function used select/deselect all checkboxes in a single click
 **/
function selectAllCheckbox(chk) {
    
    for (var i = 0; i < document.linkFrm.elements.length; i++) {
        var e = document.linkFrm.elements[i];        
        
        if (e.type == 'checkbox' && !e.disabled) {  
            e.checked = chk.checked;
        }
    }
}
/**
 * Shreeja Ravindranathan
 * Function to impose max length for a text area
 * 3 Aug 2010
 */
function imposeMaxLength(Object, MaxLen)
{
  if (Object.value.length > MaxLen) {
      Object.value = Object.value.substring(0,MaxLen);
      return false;
  } else {
      return true;
  }
//  return (Object.value.length <= MaxLen);
}

function clearAddPurchasePointsSearch() {
    document.getElementById("txtFirstName").value ="";
    document.getElementById("txtLastName").value ="";
    document.getElementById("txtEmail").value ="";
}
function allowOnlyNumeric(obj,val, e, allowDecimal, allowNegative,value) {
    var key;
    var isCtrl = false;
    var keychar;
    var reg;

    /* if ("" == val && null != document.getElementById("purchasePoint")) {
        document.getElementById("purchasePoint").value = 0;
    }*/
    var regExpression = /[^0-9\.]/;

    if (false == allowDecimal) {
        regExpression = /[^0-9]/;
    }

    /*check whether the string contains only numbers
     * This code was inserted to check for negative
     *  numbers and alphabets on copy & paste
     */
    if (true == regExpression.test(val)){
        obj.value = value;
    }

    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    //alert('key in if--->' + key);
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    //alert('key in else--->' + key);
    }

    if (isNaN(key))
    {
        //alert('in isNan If--->');
        return true;
    }

    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl) {
        return true;
    }

    //alert(allowNegative + ' ' + allowDecimal);
    reg = /[0-9.]/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    //alert('alert bool--->' + isFirstN + reg.test(keychar));

    return isFirstN || reg.test(keychar);
}

/**
 * Sreejith.P.S
 * 11.08.08
 * function used check/uncheck the main checkbox when selecting other checkbox
 **/
function uncheckMasterCheckBox() {
    var fom = document.getElementById('linkFrm:dtbtable:modifyAll')
    var incr = 0;
    var total = 0;
    for (var i = 0; i < document.linkFrm.elements.length; i++) {
        var e = document.linkFrm.elements[i];
        
        if (e.type == 'checkbox' && e.name != 'linkFrm:dtbtable:modifyAll') { 
            total = total + 1;
            if (e.checked){
                incr = incr + 1;
                
            }
        }
    }
    
    if (total == incr){        
        fom.checked = true;
    } else {    
        fom.checked = false;
    }
    
    
}

/**
 * Sreejith.P.S
 * 27.08.08
 * function used to show the rejected reason field and corresponding buttons 
 * in publishCampaign page
 **/

/**
 * Sreejith.P.S
 * 27.08.08
 * function used to hide the rejected reason field and buttons in publishCampaign page
 **/
function hideReason() {
    document.getElementById("reasonText").style.visibility="hidden";
    document.getElementById("reasonText").style.display="none";
    document.getElementById("publishForm:publish").style.visibility="visible";
    document.getElementById("publishForm:reject").style.visibility="visible";
    document.getElementById("publishForm:back").style.visibility="visible";
    document.getElementById("publishForm:submit").style.visibility="hidden";
    document.getElementById("publishForm:cancel").style.visibility="hidden";
    
    document.getElementById("approveButton").style.visibility="visible";
    document.getElementById("submitButton").style.display="none";
}


function showRegionOwner() {
    var value = document.getElementById("assignRegionOwner:regionOwnerId").value;
    var ownerId = parseInt(value);
    
    if (ownerId > 0) {
        document.getElementById("assignRegionOwner:grid").style.visibility="hidden";
        document.getElementById("assignRegionOwner:grid").style.display="none";
        document.getElementById("assignRegionOwner:txtRegionOwnerName").disabled=true;
        document.getElementById("assignRegionOwner:txtUsername").disabled=true;
        document.getElementById("assignRegionOwner:txtPassword").disabled=true;
    } else {
        document.getElementById("assignRegionOwner:grid").style.visibility="visible";
        document.getElementById("assignRegionOwner:grid").style.display='';
        document.getElementById("assignRegionOwner:txtRegionOwnerName").disabled=false;
        document.getElementById("assignRegionOwner:txtUsername").disabled=false;
        document.getElementById("assignRegionOwner:txtPassword").disabled=false;
    }
    
}

function validateAssignRegionOwner() {
    
    var ownerName = document.getElementById('assignRegionOwner:txtRegionOwnerName');
    var userName = document.getElementById('assignRegionOwner:txtUsername');
    var password = document.getElementById('assignRegionOwner:txtPassword');
    
    var ownerId = parseInt(document.getElementById("assignRegionOwner:regionOwnerId").value);
    
    
    
    // Create New value is fixed as -1
    if (ownerId > -1) {
        return true;
    }
    
    if (ownerName.value.length == 0) {
        alert("Enter Region Owner Name");
        ownerName.focus();
        return false;
    }
    
    if (userName.value.length == 0) {
        alert("Enter User Name");
        userName.focus();
        return false;
    }
    
    if (password.value.length == 0) {
        alert("Enter Password");
        password.focus();
        return false;
    }
    
    return true;
}

/**
 * Sreejith.P.S
 * 02.09.08
 * function used to validate whether user selected in assignLinkToUser page
 **/
function validateUser(){        
    var userId = document.getElementById("linkFrm:userId").value;        
    
    if (userId == "-1"){
        alert("Select a user ");
        return false
    }
    
    return true;
}


function checkRegionName() {
    var rgnName = document.getElementById("createRegion:CommercialTerms").value;
    
    if (rgnName.length==0) {
        document.getElementById("createRegion:CommercialTerms").value = " ";
    }
    
    return true;
}

function checkTerms() {
    var rgnName = document.getElementById("createRegion:CommercialTerms").value;
    var str = trim(rgnName);
    
    if (str.length==0) {
        document.getElementById("createRegion:CommercialTerms").value = "";
    }else {
        document.getElementById("createRegion:CommercialTerms").value = str;
    }
    
    
    return true;
}


function trim(str) {
    return str.replace(/^\s*|\s*$/g,"");
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used show/hide the adverts waiting to view
 **/
function displayAdvertsToView() {
    if (document.getElementById("advertToView").style.display == "none") {      
        showAdvertsToView();
    }
    else {     
        hideAdvertsToView();
    }
    
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used show the adverts waiting to view
 **/  
function hideAdvertsToView() {
    document.getElementById("advertToView").style.display = "none";
    document.getElementById("showAdv").src = "images/enduser/arwlft.gif";
    document.getElementById("summaryForm:advertsStillToView").setAttribute("class", "advertishddisabled");
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used hide the adverts waiting to view
 **/
function showAdvertsToView() {
    document.getElementById("advertToView").style.display = "block";
    document.getElementById("showAdv").src = "images/enduser/arrdown.gif";
    document.getElementById("summaryForm:advertsStillToView").setAttribute("class", "advertishd");
}


/**
 * Sreejith.P.S
 * 13.10.08
 * function used show/hide the most viewed adverts
 **/
function displayMostViewedAdverts() {
    if (document.getElementById("mostViewedAdv").style.display == "none") {      
        showMostViewedAdverts();
    }
    else {     
        hideMostViewedAdverts();
    }
    
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used show the most viewed adverts
 **/
function hideMostViewedAdverts() {
    document.getElementById("mostViewedAdv").style.display = "none";
    document.getElementById("mostViewAdv").src = "images/enduser/arwlft.gif";
    //alert(document.getElementById("mostviewdvideosmain").getAttribute("class"));//, "mostviewdvideosdisabled"));
    document.getElementById("summaryForm:mostviewdvideosmain").setAttribute("class", "mostviewdvideosdisabled");
    
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used hide the most viewed adverts
 **/
function showMostViewedAdverts() {
    document.getElementById("mostViewedAdv").style.display = "block";
    document.getElementById("mostViewAdv").src = "images/enduser/arrdown.gif";
    //alert(document.getElementById("mostviewdvideosmain").getAttribute("class"))
    document.getElementById("summaryForm:mostviewdvideosmain").setAttribute("class", "mostviewdvideos");
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used show/hide the most viewed adverts
 **/
function displayAdvertViewHistory() {
    
    if (document.getElementById("advertviewhistory").style.display == "none") {      
        showAdvertViewHistory();
    }
    else {     
        hideAdvertViewHistory();
    }
    
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used show the most viewed adverts
 **/
function hideAdvertViewHistory() {
    document.getElementById("advertviewhistory").style.display = "none";
    document.getElementById("showAdv").src = "images/enduser/arwlft.gif";
    //alert(document.getElementById("advertviewhistorymain").getAttribute("class"));//, "mostviewdvideosdisabled"));
    document.getElementById("advHistoryForm:advertviewhistorymain").setAttribute("class", "advertviewhistorydisabled");
    
}

/**
 * Sreejith.P.S
 * 13.10.08
 * function used hide the most viewed adverts
 **/
function showAdvertViewHistory() {
    document.getElementById("advertviewhistory").style.display = "block";
    document.getElementById("showAdv").src = "images/enduser/arrdown.gif";
    //alert(document.getElementById("advertviewhistorymain").getAttribute("class"))
    document.getElementById("advHistoryForm:advertviewhistorymain").setAttribute("class", "advertviewhistory");
}

/**
 * Sreejith.P.S
 * 08.11.08
 * function used change the image on mouse over
 **/
function setMouseOverStyle(compName, url, formname) {  
    var source = document.getElementById(formname+":"+compName);
    source.src = url;
}

/**
 * Sreejith.P.S
 * 08.11.08
 * function used change the image on mouse out
 **/
function setMouseOutStyle(compName, url, formname) {  
    var source = document.getElementById(formname+":"+compName);
    source.src = url;
}

/** Peeyush S
 * 02.01.09
 * Function to show progress bar on uploading
 */
function showProgressBar() {
    //alert("asdfas asfdsdaf sa fsa fsadsdaf");
    document.getElementById('abcd123').style.display='block';
//document.getElementById('survey:save').style.disabled=true;
    
}


/** Sajith.m
 * 20.01.09
 * Function to validate the phone number change  
 */
function validatePhoneNumber() {
    try {
        var val = document.getElementById("endUser:origPhone").value;
        var val1 = document.getElementById("endUser:phNo").value;
        //alert("Value is : " + val);
        //alert("Hi");
        //alert("Value Change is : " + val1);
        var answer = confirm("Did your handset change as well?")
        
        if (answer) {
            //  alert("Handset changed");
            document.getElementById("endUser:hanChanged").value = true;
        } else {
            document.getElementById("endUser:hanChanged").value = false;
        }
        
    }catch (err) {
    //alert ("Error");
    //alert(err);
    }
    
}

/**
 * Sajith.m
 * 22.01.09
 * function used show/hide the regions list in left menu
 **/
function displayRegionsList() {
    //alert("inside Regions List ");
    
    if (document.getElementById("regionByUsers").style.display == "none") {      
        showRegionsList();
    }
    else {     
        hideRegionsList();
    }
    
}

/**
 * Sajith.m
 * 22.01.09
 * function used to show regions in the left menu
 **/  
function hideRegionsList() {
    var regStr = document.getElementById("regionByUsers");
    
    if (regStr){ 
        regStr.style.display = "none";
    }
    
    var regSrc = document.getElementById("showAdv")
    
    if (regSrc) {
        regSrc.src = "images/adminuser/arwlft.gif";
    }
    
    var regClass = document.getElementById("mainForm:advertsStillToView")
    
    if (regClass) {
        regClass.setAttribute("class", "advertishddisabled");
    }
}

/**
 * Sajith.m
 * 22.01.09
 * function used hide the regions list in left menu
 **/
function showRegionsList() {
    document.getElementById("regionByUsers").style.display = "block";
    document.getElementById("showAdv").src = "images/adminuser/arrdown.gif";
    document.getElementById("mainForm:advertsStillToView").setAttribute("class", "advertishd");
}


/** Sajith.m
 * 23.01.09
 * Function to hide the feedback user name
 */
function makeUserNameAnonymous() {
    try {
        //alert("INside Make Anonymous Method");
        var obj = document.getElementById("frmFeedback:txtUserName");
        
        if (null == obj) {
        // alert("Object is NULL");
        } else {
            
            var val = document.getElementById("frmFeedback:txtUserName").value;
            var val1 = document.getElementById("frmFeedback:chkAnonymous").checked;
            
            if (val1) {
                document.getElementById("frmFeedback:txtUserName").value="";
            } else {
                // alert("User Name :: " + document.getElementById("frmFeedback:userName").value);
                document.getElementById("frmFeedback:txtUserName").value = 
                document.getElementById("frmFeedback:userName").value;
                
            }
            
        }
        
    } catch (err) {
    // alert ("Error");
    // alert(err);
    }
    
}

function clearFeedback() {
    var txtObj  = document.getElementById("frmFeedback:Comments");
    var x=document.getElementById("frmFeedback:selectCat");
    var val1 = document.getElementById("frmFeedback:chkAnonymous");
    var urgent = document.getElementById("frmFeedback:urgent");
    
    if (null != txtObj) {
        txtObj.value = "";
    }    
    
    if (null != x) {
        x.value = -1;
    }
    
    if (null != val1) {
        val1.checked = false;
        var txtusername = document.getElementById("frmFeedback:txtUserName");
        var username = document.getElementById("frmFeedback:userName");
        
        if ( (null!=txtusername) && (null != username) ) {
            txtusername.value = username.value;
        }
        
    }
    
    if (null != urgent) {
        urgent.value = 3;
    }
    
    
}

function findBrowser() {
    
    try {
        var html = "";
        var divObj  = document.getElementById("error");
        var txtObj  = document.getElementById("frmFeedback:Comments");
        var x=document.getElementById("frmFeedback:selectCat");
        divObj.innerHTML = "";
        var boolValue = true;
        
        if (x.value == -1) {
            html = "Select Severity";
            //html += "<br/>";
            divObj.innerHTML += html;
            return false;
        //boolValue = false;
        }
        
        if(txtObj.value == "" || txtObj.value.length == 0) {
            html = "Enter Comments";
            divObj.innerHTML += html;
            return false;
        //boolValue = false;
        }
        
    /**
         if (!boolValue) {
         return false;
         }
         */
        
        
    } catch(e) {
        alert(e.message)
    }
    
    
    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browserName  = navigator.appName;
    var fullVersion  = ''+parseFloat(navigator.appVersion); 
    var majorVersion = parseInt(navigator.appVersion,10);
    var nameOffset,verOffset,ix;
    
    //alert("Agent :: " + nAgt);
    
    // In MSIE, the true version is after "MSIE" in userAgent
    if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
        browserName = "Microsoft Internet Explorer";
        fullVersion = nAgt.substring(verOffset+5);
    }
    // In Opera, the true version is after "Opera" 
    else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
        browserName = "Opera";
        fullVersion = nAgt.substring(verOffset+6);
    }
    // In Chrome, the true version is after "Chrome" 
    else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
        browserName = "Chrome";
        fullVersion = nAgt.substring(verOffset+7);
    }
    // In Safari, the true version is after "Safari" 
    else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
        browserName = "Safari";
        fullVersion = nAgt.substring(verOffset+7);
    }
    // In Firefox, the true version is after "Firefox" 
    else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
        browserName = "Firefox";
        fullVersion = nAgt.substring(verOffset+8);
    }
    // In most other browsers, "name/version" is at the end of userAgent 
    else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) {
        browserName = nAgt.substring(nameOffset,verOffset);
        fullVersion = nAgt.substring(verOffset+1);
        if (browserName.toLowerCase()==browserName.toUpperCase()) {
            browserName = navigator.appName;
        }
    }
    // trim the fullVersion string at semicolon/space if present
    if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix);
    if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix);
    
    majorVersion = parseInt(''+fullVersion,10);
    if (isNaN(majorVersion)) {
        fullVersion  = ''+parseFloat(navigator.appVersion); 
        majorVersion = parseInt(navigator.appVersion,10);
    }
    
    document.getElementById("frmFeedback:browserName").value = browserName;
    
    
//alert("Browser Name = " + browserName);
//document.write('Browser name  = '+browserName+'<br>');
//document.write('Full version  = '+fullVersion+'<br>');
//document.write('Major version = '+majorVersion+'<br>');
//document.write('navigator.appName = '+navigator.appName+'<br>');
//document.write('navigator.userAgent = '+navigator.userAgent+'<br>');
}

function printValue() {
    alert('Hi SMS');
}

/**
 
 */

var SelectExceptons = new Array("frmFeedback:selectCat");

function ShowWaitWindow() {
    var dv = document.getElementById("dvWait");
    dv.className = "dvWait_V";
    dv.style.width = document.body.scrollWidth + "px";
    
    if ( document.body.scrollHeight > screen.height ) {
        dv.style.height = document.body.scrollHeight + "px";
    } else {
        dv.style.height = screen.height + "px";
    }       
    
/**
     if ( document.documentElement.offsetHeight >= document.documentElement.scrollHeight ) {
     document.getElementById("dvWait").style.height  = document.documentElement.offsetHeight + "px";
     }
     else {
     document.getElementById("dvWait").style.height  = document.documentElement.scrollHeight + "px";
     }
     **/
}



function HideWaitWindow() {
    document.getElementById("dvWait").className = "dvWait_H";
}


function ShowTopWindow() {
    document.getElementById("dvTopContent").className = "dvTopContent_V";
    ShowWaitWindow();
    ShowHideSelect( "none" );
    // clears the previously entered feedback
    clearFeedback();
}

function HideTopWindow() {
    document.getElementById("dvTopContent").className = "dvTopContent_H";
    HideWaitWindow();
    ShowHideSelect( "" );
}

function ShowHideSelect( val ) {
    var sel = document.getElementsByTagName("SELECT");
    
    for( var i=0; i < sel.length; i++ ) {
        if ( ! IsException( sel[i].id ) ) {
            sel[i].style.display = val;
        }
    }
}

function IsException( id ) {
    var result = false;
    
    for( var i=0; i < SelectExceptons.length; i++ ) {
        if ( SelectExceptons[i] == id ) {
            result = true;
            break;
        }
    }
    
    return result;
}


/**
 Script to be run when version div is to be clicked
 **/
function ShowVersionWaitWindow() {
    var dv = document.getElementById("dvVersionWait");
    
    dv.className = "dvWait_V";
    dv.style.width = document.body.scrollWidth + "px";
    
    if ( document.body.scrollHeight > screen.height ) {
        dv.style.height = document.body.scrollHeight + "px";
    } else {
        dv.style.height = screen.height + "px";
    }   
    
/**
     if ( document.documentElement.offsetHeight >= document.documentElement.scrollHeight ) {
     document.getElementById("dvVersionWait").style.height  = document.documentElement.offsetHeight + "px";
     }
     else {
     document.getElementById("dvVersionWait").style.height  = document.documentElement.scrollHeight + "px";
     }
     **/
}

function HideVersionWaitWindow() {
    document.getElementById("dvVersionWait").className = "dvWait_H";
}

function ShowVersionTopWindow() {
    document.getElementById("dvVersionContent").className = "dvTopContentAbout_V";
    ShowVersionWaitWindow();
    ShowHideSelect( "none" );
    showFlashDiv();
}

function HideVersionTopWindow() {
    document.getElementById("dvVersionContent").className = "dvTopContentAbout_H";
    HideVersionWaitWindow();
    ShowHideSelect( "" );
    hideFlashDiv();
}


/////////////////////////////////////////////

/**
 Scripts to be run when the enduser profile handset changed
 **/

function ShowWaitWindowProfile() {
    var dv = document.getElementById("dvWait");
    dv.className = "dvWait_V";
    
    dv.style.width = document.body.scrollWidth + "px";
    
    
    if ( document.body.scrollHeight > screen.height ) {
        dv.style.height = document.body.scrollHeight + "px";
        
    } else {
        dv.style.height = screen.height + "px";
        
    }   
    
/**
     if ( document.documentElement.offsetHeight >= document.documentElement.scrollHeight ) {
     document.getElementById("dvWait").style.height  = document.documentElement.offsetHeight + "px";
     }
     else {
     document.getElementById("dvWait").style.height  = document.documentElement.scrollHeight + "px";
     }
     **/
}

function HideWaitWindowProfile() {
    document.getElementById("dvWait").className = "dvWait_H";
}

function ShowTopWindowProfile() {
    document.getElementById("dvTopContentProfile").className = "dvTopContentProfile_V";
    ShowWaitWindowProfile();
    ShowHideSelect( "none" );
    return false;
}

function HideTopWindowProfile() {
    document.getElementById("dvTopContentProfile").className = "dvTopContentProfile_H";
    HideWaitWindowProfile();
    ShowHideSelect( "" );
}

function HideTopWindowYes() {
    HideTopWindowProfile();
    document.getElementById("endUser:hanChanged").value = true;
    return true;
}

function HideTopWindowNo() {
    HideTopWindowProfile();
    document.getElementById("endUser:hanChanged").value = false;
    return true;
}

function HideTopWindowConfirmationYes() {
    HideTopWindowProfile();
    return true;
}

function HideTopWindowConfirmationNo() {
    HideTopWindowProfile();
    return false;
}


/**
 Script to be run when under construction div is to be clicked
 **/
function ShowConstructWaitWindow() {
    var dv = document.getElementById("dvConstructWait");
    dv.className = "dvConstruct_V";
    
    dv.style.width = document.body.scrollWidth + "px";
    
    
    if ( document.body.scrollHeight > screen.height ) {
        dv.style.height = document.body.scrollHeight + "px";
        
    } else {
        dv.style.height = screen.height + "px";
        
    }       
    
/**
     if ( document.documentElement.offsetHeight >= document.documentElement.scrollHeight ) {
     document.getElementById("dvConstructWait").style.height  = document.documentElement.offsetHeight + "px";
     } else {
     document.getElementById("dvConstructWait").style.height  = document.documentElement.scrollHeight + "px";
     }
     **/
    
}

function HideConstructWaitWindow() {
    document.getElementById("dvConstructWait").className = "dvConstruct_H";
}

function ShowConstructTopWindow() {
    document.getElementById("dvConstructContent").className = "dvTopContentConstruct_V";
    hideFlashDiv();
    ShowConstructWaitWindow();
    ShowHideSelect( "none" );
}


function hideFlashDiv() {
    var obj = document.getElementById("homeFlashcommercial");
    
    if (null != obj) {
        obj.style.visibility = 'hidden';
    }
    
    var flash = document.getElementById("subContentVideoBox");
    
    if (null != flash) {
        flash.style.visibility = 'hidden';
    }
    
}


function HideConstructTopWindow() {
    document.getElementById("dvConstructContent").className = "dvTopContentConstruct_H";
    HideConstructWaitWindow();
    ShowHideSelect( "" );
    
    showFlashDiv();
    
}

function showFlashDiv() {
    var obj = document.getElementById("homeFlashcommercial");
    
    if (null != obj) {
        obj.style.visibility = 'visible';
    }
    
    var flash = document.getElementById("subContentVideoBox");
    
    if (null != flash) {
        flash.style.visibility = 'visible';
    }
    
}



/**
 Validating the date field
 **/

function ValidateDateField() {
    
    return validateDate('regionList:searchDate');
/**
     alert("Inside validating the date field");
     alert("Day is : " + document.getElementById('regionList:searchDate.day').value);
     alert("Month is : " + document.getElementById('regionList:searchDate.month').value);
     alert("Year is : " + document.getElementById('regionList:searchDate.year').value);
     **/
    
/**
     var day = document.getElementById('regionList:searchDate.day').value;
     var month = document.getElementById('regionList:searchDate.month').value;
     var year = document.getElementById('regionList:searchDate.year').value;
     var errFlag = true;
     
     if ( (day.length == 0) && (month == -1) && (year.length == 0) ) {
     alert("Date is Empty");
     return errFlag;
     } else {
     // date is not empty
     
     if (day.length  == 0) {
     alert("Please enter the day");
     errFlag = false;
     } else if (month == -1) {
     alert("Please select month");
     errFlag = false;
     } else if (year.length == 0) {
     alert("Please select year");
     errFlag = false;    
     } else if (isNaN(day)) {
     alert("Please enter a valid day");
     errFlag = false;    
     } else if (isNaN(year)) {
     alert("Please enter a valid year");
     errFlag = false;    
     }
     
     }
     
     } catch (err) {
     alert(err.message);
     }
     
     return errFlag;
     **/
}

/*
 * adds startswith method to string
 */
String.prototype.startsWith = function(str) {
    return (this.match("^"+str)==str);
}

/*
 * adds endswith method to string
 */
String.prototype.endsWith = function(str) {
    return (this.match(str+"$")==str);
}

/**
 * validates all JSF date fields  (used in admin: search fields)
 */
function validateAllDateElements() {
    var status = true;
    var selectElements = document.getElementsByTagName("select");

    for (var i=0; i < selectElements.length; i++) {
        var elementId = selectElements[i].id;

        if (elementId.endsWith('month')) {
            var dateElementId = elementId.substring(0, elementId.indexOf(".month"));

            if (!validateDate(dateElementId)) {
                status = false;
                break;
            } // end of if
        } // end of if
    } // end of for
    return status;
}

/**
 * clears all JSF date fields  (used in admin: search fields)
 */
function clearAllDateElements() {
    var selectElements = document.getElementsByTagName("select");

    for (var i=0; i < selectElements.length; i++) {
        var elementId = selectElements[i].id;

        if (elementId.endsWith('month')) {
            var dateElementId = elementId.substring(0, elementId.indexOf(".month"));

            clearDateField(dateElementId);
        } // end of if
    } // end of for
}

function dateValidation() {
    return (validateDate('approvalList:searchDate') && validateDate('approvalList:beforeDate'));
}

function validateDate(elem) {
    try {
        var errFlag = true;
        var objDay = document.getElementById(elem+'.day');
        var objMon = document.getElementById(elem+'.month');
        var objYear = document.getElementById(elem+'.year');
        var day = document.getElementById(elem+'.day').value;
        var month = document.getElementById(elem+'.month').value;
        var year = document.getElementById(elem+'.year').value;
        
        
        if ( (day.length == 0) && (month == -1) && (year.length == 0) ) {
            // alert("Date is Empty");
            return errFlag;
        } else {
            // date is not empty
            
            if (day.length  == 0) {
                alert("Please enter the day");
                objDay.focus();
                errFlag = false;
            }else if (isNaN(day)) {
                alert("Please enter a valid day");
                objDay.focus();
                errFlag = false;    
            } else if (month == -1) {
                alert("Please select month");
                objMon.focus();
                errFlag = false;
            } else if (year.length == 0) {
                alert("Please select year");
                objYear.focus();
                errFlag = false;    
            } else if (isNaN(year)) {
                alert("Please enter a valid year");
                objYear.focus();
                errFlag = false;    
            } else if (year.length < 4) {
                alert("Please enter a valid year");
                objYear.focus();
                errFlag = false;    
            } else {
                var dateObj = new Date(year, month-1, day);
                if ((dateObj.getMonth()+1 != month)||(dateObj.getDate()!= day)
                    ||(dateObj.getFullYear()!= year)) {
                    alert("Please enter a valid date");
                    objDay.focus();
                    errFlag = false;
                }
            }
        }
    }catch (err) {
    //alert(err.message);
    }
    
    return errFlag;
}

function clearAllDateFields() {
    //  alert("In Clearing The Fields");
    clearDateField('advRepForm:startDate');
    clearDateField('advRepForm:endDate');
    // alert("After Clearing the fields");
    return true;
}

function clearDateField(elem) {
    try {
        var day = document.getElementById(elem+'.day').value = "";
        var month = document.getElementById(elem+'.month').value = "-1";
        var year = document.getElementById(elem+'.year').value = "";
    }catch (err) {
    }
}

function clearDemographics() {
    clearDateField('regionList:searchDate');
}

/** validate advertiser reports **/
function validateAdvReportDate() {
    return (validateDate('advRepForm:searchDate') && validateDate('advRepForm:endDate'));
}

function checkDateField(elem) {
    var dateObj = document.getElementById(elem+'.day');
    allow_numeric2(dateObj);
    var yearObj = document.getElementById(elem+'.year');
    allow_numeric2(yearObj);
}

function allow_numeric(obj){
    if (/[^+0-9]/i.test(obj.value))
        obj.value=obj.value.replace(/[^+0-9]/g,'')
    obj.value+=''
    obj.focus()
}

function allow_numeric2(obj){
    if (/[^+0-9]/i.test(obj.value))
        obj.value=obj.value.replace(/[^+0-9]/g,'');
    obj.value+='';
}


function showUpload(){
    document.getElementById("frmBasicInfo:imgDiv").style.display = 'block';
    document.getElementById("frmBasicInfo:imgDiv").style.visibility = 'visible';
//document.getElementById("frmBasicInfo:flImage").focus();  this is not working
//document.getElementById("falselink").focus(); //focus to the invisible link
}   

function hideAndShow(){
    try { 
        var fileObject = document.getElementById("frmBasicInfo:flImage");
        var divObj = document.getElementById("frmBasicInfo:photoDiv");
        divObj.style.display = 'none';
        var divRm = document.getElementById("frmBasicInfo:rmvDiv");
        
        var html = ' <a href="#" onClick="showFile()"> Remove</a>'
        divRm.innerHTML = fileObject.value + html;
        divRm.style.display = 'block';
        
        var imgObj = document.getElementById("frmBasicInfo:imgDiv");
        imgObj.style.visibility  ='hidden';
        imgObj.style.display = 'none';
    }catch(e) {
    // alert(e.message);
    }
    
}

function showFile() {
    var divObj = document.getElementById("frmBasicInfo:photoDiv");
    divObj.style.display = 'block'; 
    divObj.style.visibility = 'visible';
    var fileObject = document.getElementById("frmBasicInfo:flImage");
    fileObject.value = '';
    //fileObject.style.display = 'none';
    var imgObj = document.getElementById("frmBasicInfo:imgDiv");
    imgObj.innerHTML = '<input type="file" id="frmBasicInfo:flImage" name="frmBasicInfo:flImage" onchange="hideAndShow();" /><p style="font-size:11px;">Dimensions: 126x126 pixels<br  />Max.size: 20MB</p>';
    imgObj.style.display = 'none';
    var divRm = document.getElementById("frmBasicInfo:rmvDiv");
    divRm.style.display = 'none';
/*window.frmBasicInfo.reset();*/
}

/**
 * Sajith.m
 *   
 * creates and retrieves the browser http object
 */
function createHttpObject() {
    var xmlHttp = null;
    
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            
            try {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
            
        }
        
    }
    
    return xmlHttp;
}

/**
 * Sajith.m
 * Retrieves more values from network details in endusercashout page
 */
function getMoreNetWorkModel() {
    
    try {
        var count =  1;	
        var xmlHttp = createHttpObject();
        
        /** take the shown number of network level */
        var hdnObj = document.getElementById('frmCashout:hdnCurNetworkNum');
        count = hdnObj.value;
        
        var url = "enduserNetworkModelAjax.jsp?count=" + count;
        //alert("calling before function");
        xmlHttp.onreadystatechange=function() {
            
            if(xmlHttp.readyState==4) {
                var data = xmlHttp.responseText;
                //alert(data);
                var arrayData = data.split("|||");
                
                /*
                                    The parameters are seperated by ||| 
                                    0) count of the record -1 : while time out in the jsp page
                                    1) html content 
                 */
                var html = arrayData[1];
                var count = arrayData[0];
                count = trim(count);
                
                if (count == "-1") {
                    //for refreshing the page
                    location.reload(true);
                //   window.location = "timeOut.jsp"
                }else {
                    var totalView = document.getElementById('frmCashout:hdnTotalNetworkLevel').value;
                    
                    //alert("count " + count + "  totalView " + totalView);
                    if (parseInt(count) >= parseInt(totalView) ) {
                        //  alert("count " + count + "  totalView " + totalView);
                        document.getElementById('frmCashout:dvMoreNetwork').style.display = 'none';
                    }
                    
                    /** Increment the current shown network level count **/
                    document.getElementById('frmCashout:hdnCurNetworkNum').value = count;
                    
                    var tableObj = document.getElementById('dvNetwork');
                    tableObj.innerHTML = html;
                }
                hideToViewNetworkDiv();
                xmlHttp = null;
            } else {
                showToViewNetworkDiv();
            }
        } // end of onready state change method
        
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    } catch(e) {
        alert(e.message);
    }
    
    return false;
}

/**
 * Sajith.m
 * Shows the toviewnetwork loading animation
 */
function showToViewNetworkDiv() {    
    document.getElementById('dvToViewNetwork').style.display='block';
}

/**
 * Sajith.m
 * hides the toviewnetwork loading animation
 */
function hideToViewNetworkDiv() {
    document.getElementById('dvToViewNetwork').style.display='none';
} 


/**
 * Sajith.m
 * Retrieves more values from network details in endusercashout page
 */
function getMoreViewedAds() {
    
    try {
        var count =  1;	
        var xmlHttp = createHttpObject();
        
        var hdnObj = document.getElementById('frmCashout:hdnCurViewedNum');
        count = hdnObj.value;
        var url = "enduserViewHistoryAjax.jsp?count=" + count;
        //alert("calling before function");
        xmlHttp.onreadystatechange=function() {
            
            if (xmlHttp.readyState==4) {
                var data = xmlHttp.responseText;
                //alert(data);
                var arrayData = data.split("|||");
                
                /*
                                    The parameters are seperated by ||| 
                                    0) count of the record -1 : while time out in the jsp page
                                    1) html content 
                 */
                var html = arrayData[1];
                var count = arrayData[0];
                count = trim(count);
                
                if (count == "-1") {
                    //for refreshing the page
                    location.reload(true);
                //   window.location = "timeOut.jsp"
                }else {
                    
                    
                    var totalView = document.getElementById('frmCashout:hdnTotalViewedAds').value;
                    // alert("count " + count + "  totalView " + totalView);
                    if (parseInt(count) >= parseInt(totalView) ) {
                        //  alert("count " + count + "  totalView " + totalView);
                        document.getElementById('frmCashout:dvMoreViewHistory').style.display = 'none';
                    }
                    document.getElementById('frmCashout:hdnCurViewedNum').value = count;
                    
                    
                    var tableObj = document.getElementById('dvViewHistory');
                    tableObj.innerHTML = html;
                }
                hideViewedAdHistory();
                xmlHttp = null;
            }else {
                showViewedAdHistory();
            }
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }catch(e) {
        alert(e.message);
    }
    
    return false;
}


/**
 * Sajith.m
 * Shows the viewed ad history loading animation image
 */
function showViewedAdHistory() {    
    //alert("Hi ");
    document.getElementById('dvViewedAdHistory').style.display='block';
}

/**
 * Sajith.m
 * hides the view ad history loading animation image
 */
function hideViewedAdHistory() {
    document.getElementById('dvViewedAdHistory').style.display='none';
} 

/**
 * Sajith.m
 * used to focus the div when clicked on the anchor tag on the view page
 */
function focusDiv() {
    
    var elem = document.getElementById('divUnWatchedAds');
    document.getElementById("emailMsgId").style.display = 'none';
    
    /* will not work in IE as ie calculates top relative to the enclosed or 
     * parent component */
    // window.scrollTo(0, document.getElementById('divMostWatched').offsetTop);
    var dim = GetTopLeft(elem);
    
    window.scrollTo(0, dim.Top);
    
    return false;
}

/*
 * Sajith.m
 * Calculates & returns the top & left offset of the components
 */
function GetTopLeft(elm) {
    var x, y = 0;
    
    //set x to elm’s offsetLeft
    x = elm.offsetLeft;
    
    //set y to elm’s offsetTop
    y = elm.offsetTop;
    
    //set elm to its offsetParent
    elm = elm.offsetParent;
    
    //use while loop to check if elm is null
    // if not then add current elm’s offsetLeft to x
    //offsetTop to y and set elm to its offsetParent
    
    while(elm != null) {
        
        x = parseInt(x) + parseInt(elm.offsetLeft);
        y = parseInt(y) + parseInt(elm.offsetTop);
        elm = elm.offsetParent;
    }
    
    //here is interesting thing
    //it return Object with two properties
    //Top and Left
    
    return {
        Top:y,
        Left: x
    };
}

function validateAddressInfo() {
    // hidden address details in the payment form
    var hdnPaypalAddr1 = document.getElementById("frmBasicInfo:hdnPaypalAddr1");
    var hdnPaypalAddr2 = document.getElementById("frmBasicInfo:hdnPaypalAddr2");
    
    var hdnPaypalCity = document.getElementById("frmBasicInfo:hdnPaypalCity");
    var hdnPaypalState = document.getElementById("frmBasicInfo:hdnPaypalState");
     
    var hdnPaypalPostCode = document.getElementById("frmBasicInfo:hdnPaypalPostCode"); 
    
    // entered address details in the address form
    var addr1 =   document.getElementById("frmBasicInfo:addr1"); 
    var addr2 = document.getElementById("frmBasicInfo:addr2");
    
    var city = document.getElementById("frmBasicInfo:city");
    var state = document.getElementById("frmBasicInfo:state");
    
    var postCode = document.getElementById("frmBasicInfo:postCode");   
    var status = true;
    
    if (hdnPaypalAddr1.value.length > 0 || hdnPaypalAddr1.value == '') {
        status = isSameString(hdnPaypalAddr1.value, addr1.value);
        
        if (status == false) {
            // alert("both address1 are not same");
            showAndAddAddressMessage("You sure about that? Your PayPal address must match the address you provided in the Address section.");
            return status;
        }
        
    } 
    
    if (hdnPaypalAddr2.value.length > 0 || hdnPaypalAddr2.value == '') {
        status = isSameString(hdnPaypalAddr2.value, addr2.value);
        
        if (status == false) {
            //alert("both address2 are not same");
            showAndAddAddressMessage("You sure about that? Your PayPal address must match the address you provided in the Address section.");
            return status;
        }        
        
    } 
    
    if (hdnPaypalPostCode.value.length > 0 || hdnPaypalPostCode.value == '') {
        status = isSameString(trim(hdnPaypalPostCode.value), trim(postCode.value));
        
        if (status == false) {
            //alert("both zip code are not same");
            showAndAddAddressMessage("You sure about that? The zip code you enter here must match the one you provided in the Address section.");
            return status;
        }         
        
    } // end of else condition

    if (hdnPaypalCity.value.length > 0 || hdnPaypalCity.value == '') {

        status = isSameString(trim(hdnPaypalCity.value), trim(city.value));
        
        if (status == false) {

            showAndAddAddressMessage("You sure about that? The zip code you enter here must match the one you provided in the Address section.");
            return status;
        }         
        
    } // end of else condition

    if (hdnPaypalState.value.length > 0 || hdnPaypalState.value == '') {

        status = isSameString(trim(hdnPaypalState.value), trim(state.value));
        
        if (status == false) {

            showAndAddAddressMessage("You sure about that? The zip code you enter here must match the one you provided in the Address section.");
            return status;
        }         
        
    } // end of else condition
    
    return true;
}

function validatePaymentInfo() {

    // hidden address details in the address form
    var hdnAddr1 = document.getElementById("frmBasicInfo:hdnAddr1");
    var hdnAddr2 = document.getElementById("frmBasicInfo:hdnAddr2");

    
    var hdnCity = document.getElementById("frmBasicInfo:hdnCity");
    var hdnState = document.getElementById("frmBasicInfo:hdnState");
     
    var hdnPostCode = document.getElementById("frmBasicInfo:hdnPostCode");
    
    // entered address details in the payment form
    var paypalAddr1 =   document.getElementById("frmBasicInfo:paypalAddr1"); 
    var paypalAddr2 = document.getElementById("frmBasicInfo:paypalAddr2");
    
    var paypalCity = document.getElementById("frmBasicInfo:paypalCity");
    var paypalState = document.getElementById("frmBasicInfo:paypalState");
    
    var paypalPostCode = document.getElementById("frmBasicInfo:paypalZipCode");        
    var status = true;
    
    if (hdnAddr1.value.length > 0 || hdnAddr1.value == '') {
        status = isSameString(hdnAddr1.value, paypalAddr1.value);
        // alert(hdnAddr1.value);
        if (status == false) {
            //alert("both address1 are not same");
            showAndAddMessage("You sure about that? Your PayPal address must match the address you provided in the Address section.");
            return status;
        }
        
    } 
    
    if (hdnAddr2.value.length > 0 || hdnAddr2.value == '') {
        status = isSameString(hdnAddr2.value, paypalAddr2.value);
        
        if (status == false) {
            //alert("both address2 are not same");
            showAndAddMessage("You sure about that? Your PayPal address must match the address you provided in the Address section.");
            return status;
        }        
        
    } 
    
    if (hdnPostCode.value.length > 0 || hdnPostCode.value == '') {
        status = isSameString(trim(hdnPostCode.value), trim(paypalPostCode.value));
        
        if (status == false) {
            // alert("both zip code are not same");
            showAndAddMessage("You sure about that? The zip code you enter here must match the one you provided in the Address section.");
            return status;
        }         
        
    } // end of else condition

    if (hdnCity.value.length > 0 || hdnCity.value == '') {
        status = isSameString(trim(hdnCity.value), trim(paypalCity.value));
        
        if (status == false) {

            showAndAddMessage("You sure about that? The zip code you enter here must match the one you provided in the Address section.");
            return status;
        }         
        
    } // end of else condition

    if (hdnState.value.length > 0 || hdnState.value == '') {
        status = isSameString(trim(hdnState.value), trim(paypalState.value));
        
        if (status == false) {

            showAndAddMessage("You sure about that? The zip code you enter here must match the one you provided in the Address section.");
            return status;
        }         
        
    } // end of else condition
    
    return true;
}

function isSameString( s1, s2 ) {
    
    if ( s1.toString() == s2.toString() ) {
        return true;
    }else {
        return false;
    }
    
}

function showAndAddMessage(msg) {
    ShowPaymentMsgWaitWindow();
    document.getElementById("confirmMsg").innerText = msg;
}
/**
 * checks for mismatch between Address & payment Address
 *
 */
function checkAddressMismatch() {
    // address fields
    var addr1 =   document.getElementById("addr1").value;
    var addr2 = document.getElementById("addr2").value;
    var city = document.getElementById("city").value;
    var state = document.getElementById("state").value;
    var zipCode = document.getElementById("zipCode").value;

    // paypal address fields
    var paypalAddr1 = document.getElementById("paypalAddr1").value;
    var paypalAddr2 = document.getElementById("paypalAddr2").value;
    var paypalCity = document.getElementById("paypalCity").value;
    var paypalState = document.getElementById("paypalState").value;
    var paypalzipCode = document.getElementById("paypalZipCode").value;
    var status = false;

    if ((addr1 != paypalAddr1) || (addr2 != paypalAddr2) || (city != paypalCity)
        || (state != paypalState)) {
        document.getElementById("mesgDiv").innerHTML = "You sure about that? Your PayPal address must match the address you provided in the Address section.";
        couponPopup(1);
        scroll(0,0);
    } else if (zipCode != paypalzipCode) {
        document.getElementById("mesgDiv").innerHTML = "You sure about that? Your PayPal zip code must match the one you provided in the Address section.";
        couponPopup(1);
        scroll(0,0);
    } else {
        status = true;
    }
    return status;
}

function ShowPaymentMsgWaitWindow() {
    
    if (null != document.getElementById("dvPaymentContent")) {
        document.getElementById("dvPaymentContent").className = "dvTopContentConstruct_V";
        ShowPaymentMsgWindow();
    }
    
    //ShowHideSelect( "none" );
    return false;
}

function ShowPaymentMsgWindow() {
    var dv = document.getElementById("dvPaymentWait");
    
    if (null != dv) {
        dv.className = "dvConstruct_V";
        //dv.className = "dialog-mask";
        //dv.style.width = document.body.scrollWidth + "px";
        dv.style.width = pageWidth() + "px";
        
        if ( document.body.scrollHeight > screen.height ) {
            dv.style.height = document.body.scrollHeight + "px";
        }else {
            dv.style.height = screen.height + "px";
        }    
        
    }
    
/** Commented not working in IE when the screen height is greater view area
     if ( document.documentElement.offsetHeight >= document.documentElement.scrollHeight ) {
     document.getElementById("dvPaymentWait").style.height  = document.documentElement.offsetHeight + "px";
     } else {
     document.getElementById("dvPaymentWait").style.height  = document.documentElement.scrollHeight + "px";
     }
     **/
}

function findPosX(obj) {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) {
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}



function HidePaymentTopWindow() {
    document.getElementById("dvPaymentContent").className = "dvTopContentConstruct_H";
    HidePaymentWaitWindow();
}

function HidePaymentWaitWindow() {
    document.getElementById("dvPaymentWait").className = "dvConstruct_H";
}

function showAndAddAddressMessage(msg) {
    ShowAddressMsgWaitWindow();
    document.getElementById("addrConfirmMsg").innerText = msg;
}

function ShowAddressMsgWaitWindow() {
    document.getElementById("dvAddressContent").className = "dvTopContentConstruct_V";
    ShowAddressMsgWindow();
    //ShowHideSelect( "none" );
    return false;
}

function ShowAddressMsgWindow() {
    var dv = document.getElementById("dvAddressWait");
    
    dv.className = "dvConstruct_V";
    //dv.style.width = document.body.scrollWidth + "px";
    dv.style.width = pageWidth() + "px";
    
    if ( document.body.scrollHeight > screen.height ) {
        dv.style.height = document.body.scrollHeight + "px";
    } else {
        dv.style.height = screen.height + "px";
    }     
    
/** Commented not working in IE when the screen height is greater view area
     if ( document.documentElement.offsetHeight >= document.documentElement.scrollHeight ) {
     document.getElementById("dvAddressWait").style.height  = document.documentElement.offsetHeight + "px";
     } else {
     document.getElementById("dvAddressWait").style.height  = document.documentElement.scrollHeight + "px";
     }
     **/
}

function HideAddressTopWindow() {
    document.getElementById("dvAddressContent").className = "dvTopContentConstruct_H";
    HideAddressWaitWindow();
}

function HideAddressWaitWindow() {
    document.getElementById("dvAddressWait").className = "dvConstruct_H";
}


function ExpandDivOnReSize() {
    var addrDiv = document.getElementById("dvAddressWait");
    var divstyle = new String();
    
    if (null != addrDiv) {
        divstyle = addrDiv.style.display;        
        
        if (divstyle.toLowerCase()=="block" || divstyle == "") {
            //alert("inside address is shown : display block1" + divstyle);
            addrDiv.style.width = pageWidth() + "px";
        }
        
    }
    
    var payDiv = document.getElementById("dvPaymentWait");
    
    if (null != payDiv) {
        divstyle = addrDiv.style.display;    
        
        if (divstyle.toLowerCase()=="block" || divstyle == "") {
            // alert("inside payment is shown : display block1" + divstyle);
            payDiv.style.width = pageWidth() + "px";
        }
        
    }
    
}

// calculate the current window width //
function pageWidth() {
    return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

/**
 * Shows the confirm referer page
 *
 */
function showRmvRefererConfirmation(objId) {
    document.getElementById("endUserViewId:confirmationBox:hdnRefId").value = objId;
    ShowPaymentMsgWaitWindow();
    return false;
}

function showPayToCharityConfirmation(objId){
    document.getElementById("")
}

function addMessage(msg) {
    var msgDiv = document.getElementById("msgDiv");
    msgDiv.innerHTML = msg;
    
    if (msg.length > 0) {
        focusDiv1(msgDiv);
        msgDiv.focus();
        msgDiv.scrollIntoView(true);
        return false;
    }
    
}


/**
 * Sajith.m
 * used to focus the div when clicked on the anchor tag on the view page
 */
function focusDiv1(div) {
    
    /* will not work in IE as ie calculates top relative to the enclosed or 
     * parent component */
    // window.scrollTo(0, document.getElementById('divMostWatched').offsetTop);
    var dim = GetTopLeft(div);
    
    //alert(" Dim Top Is  :: " + dim.Top);
    window.scrollTo(0, dim.Top);
    
    return false;
}

function clearErrMsgDiv() {
    var errMsgDiv = document.getElementById("frmBeezagCares:tblCharityMsg");
    
    if (errMsgDiv) {
        errMsgDiv.innerHTML = "";
    }
    
}

function cashoutValidation(elem) {
    //alert("id is " + elem.id);
    var objPaypalAmount = document.getElementById("frmBeezagCares:paypalAmount");
    var objCharityAmount1 = document.getElementById("frmBeezagCares:chList:0:charityName");
    var objCharityAmount2 = document.getElementById("frmBeezagCares:chList:1:charityName");
    var objCharityAmount3 = document.getElementById("frmBeezagCares:chList:2:charityName");
    var paypalAmount = 0;
    var charityAmount1 = 0;
    var chartiyAmount2 = 0;
    var charityAmount3 = 0;
    var origAmount = document.getElementById("frmBeezagCares:balance");
    var amount = document.getElementById("frmBeezagCares:hdnTotal").value;
    var totalAmount = 0.0;
    //alert(amount);
    if (null != objPaypalAmount) {
        // alert("pa" + objPaypalAmount.value);
        paypalAmount = parseFloat(objPaypalAmount.value);
    }
    
    if (null != objCharityAmount1) {
        //  alert("ch1" + objCharityAmount1.value);
        charityAmount1 = parseFloat(objCharityAmount1.value);
    }    
    
    if (null != objCharityAmount2) {
        //alert("ch2" + objCharityAmount2.value);
        chartiyAmount2 = parseFloat(objCharityAmount2.value);
    }
    
    if (null != objCharityAmount3) {
        // alert("ch3" + objCharityAmount3.value);
        charityAmount3 = parseFloat(objCharityAmount3.value);
    }
    
    if ( !isNaN(paypalAmount) ) {
        totalAmount += paypalAmount;
    }else {
        paypalAmount = 0;
    }
    
    if ( !isNaN(charityAmount1) ) {
        totalAmount += charityAmount1;
    } else {
        charityAmount1 = 0;
    }  
    
    if ( !isNaN(chartiyAmount2) ) {
        totalAmount += chartiyAmount2;
    } else {
        chartiyAmount2 = 0;
    }      
    
    if ( !isNaN(charityAmount3) ) {
        totalAmount += charityAmount3;
    } else {
        charityAmount3 = 0;
    }        
    
    amount = new Number(amount);
    totalAmount = new Number(totalAmount);
    totalAmount = totalAmount.toFixed(2);
    
    if ((totalAmount > amount) ){
        // alert("tot Amount " + totalAmount);
        // alert("Amount " + amount);
        //  alert("Total Greater Than Sum");
        addMessage("Amount exceeds remaining total");

        if (elem) {
            var totAm = amount - (totalAmount - elem.value);
            totAm = new Number(totAm);
            origAmount.value = totAm.toFixed(2);
            elem.value = "0.00";
        //elem.focus();
        }
        
        clearErrMsgDiv();
        return false;
    }else {
        addMessage("");
        clearErrMsgDiv();
    }
    
    var tot =  amount - totalAmount;
    tot = new Number(tot);
    origAmount.value = tot.toFixed(2);
    
    //origAmount.value.toFixed(2);
    // alert("value" + totalAmount);
    return true;
}

function cashoutValidationSubmit() {
    var objPaypalAmount = document.getElementById("frmBeezagCares:paypalAmount");
    var objCharityAmount1 = document.getElementById("frmBeezagCares:chList:0:charityName");
    var objCharityAmount2 = document.getElementById("frmBeezagCares:chList:1:charityName");
    var objCharityAmount3 = document.getElementById("frmBeezagCares:chList:2:charityName");
    var paypalAmount = 0;
    var charityAmount1 = 0;
    var chartiyAmount2 = 0;
    var charityAmount3 = 0;
    var origAmount = document.getElementById("frmBeezagCares:balance");
    var amount = document.getElementById("frmBeezagCares:hdnTotal").value;
    var totalAmount = 0.0;
    
    if (null != objPaypalAmount) {
        // alert("pa" + objPaypalAmount.value);
        paypalAmount = parseFloat(objPaypalAmount.value);
    }
    
    if (null != objCharityAmount1) {
        //  alert("ch1" + objCharityAmount1.value);
        charityAmount1 = parseFloat(objCharityAmount1.value);
    }    
    
    if (null != objCharityAmount2) {
        //alert("ch2" + objCharityAmount2.value);
        chartiyAmount2 = parseFloat(objCharityAmount2.value);
    }
    
    if (null != objCharityAmount3) {
        // alert("ch3" + objCharityAmount3.value);
        charityAmount3 = parseFloat(objCharityAmount3.value);
    }
    
    if ( !isNaN(paypalAmount) ) {
        totalAmount += paypalAmount;
    } else {
        paypalAmount = 0;
    }
    
    if ( !isNaN(charityAmount1) ) {
        totalAmount += charityAmount1;
    }else {
        charityAmount1 = 0;
    }  
    
    if ( !isNaN(chartiyAmount2) ) {
        totalAmount += chartiyAmount2;
    }else {
        chartiyAmount2 = 0;
    }      
    
    if ( !isNaN(charityAmount3) ) {
        totalAmount += charityAmount3;
    } else {
        charityAmount3 = 0;
    }        
    
    totalAmount = new Number(totalAmount);
    totalAmount = totalAmount.toFixed(2);
    amount = new Number(amount);
    
    if (totalAmount > amount) {
        //  alert("Total Greater Than Sum");
        addMessage("Amount exceeds remaining total");
        clearErrMsgDiv();
        return false;
    } else if (totalAmount < amount) {
        addMessage("Please allocate all your earnings.");
        clearErrMsgDiv();
        return false;
    }
    
    var tot =  amount - totalAmount;
    tot = new Number(tot);
    origAmount.value = tot.toFixed(2);
    // alert("value" + totalAmount);
    return true;
}


/* version: beta
 * created: 2005-08-30
 * updated: 2005-08-31
 * mredkj.com
 */ 
function extractNumber(obj, decimalPlaces, allowNegative) {
    var temp = obj.value;
    
    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\\.?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;
    
    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');
    
    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }
    
    if (decimalPlaces != 0) {
        var reg3 = /\./g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
        }
    }
    
    obj.value = temp;
}
/**
 * Fuction to block non numbers
 *
 */
function blockNonNumbers(obj, e, allowDecimal, allowNegative) {
    var key;
    var isCtrl = false;
    var keychar;
    var reg;
    
    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }
    
    if (isNaN(key)) return true;
    
    keychar = String.fromCharCode(key);
    
    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl) {
        return true;
    }
    
    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
    
    return isFirstN || isFirstD || reg.test(keychar);
}

/**
 * Sajith.m
 * used to focus the div when clicked on the anchor tag on the view page
 */
function focusCoupons() {
    
    var elem = document.getElementById('couponThumbnailsId');
    var emailMsg = document.getElementById("emailMsgId");
    
    if (emailMsg) {
        emailMsg.style.display = 'none';
    }
    
    /* will not work in IE as ie calculates top relative to the enclosed or 
     * parent component */
    // window.scrollTo(0, document.getElementById('divMostWatched').offsetTop);
    var dim = GetTopLeft(elem);
    
    window.scrollTo(0, dim.Top);
    
    return false;
}

/**
 * Sajith.m
 * used to focus the div when clicked on the anchor tag on the view page
 */
function focusRecentlyWatchedAds() {
    
    var elem = document.getElementById('recentlyWatchedAdvAds');
    var emailMsg = document.getElementById("emailMsgId");
    
    if (emailMsg) {
        emailMsg.style.display = 'none';
    }
    
    /* will not work in IE as ie calculates top relative to the enclosed or 
     * parent component */
    // window.scrollTo(0, document.getElementById('divMostWatched').offsetTop);
    var dim = GetTopLeft(elem);
    
    window.scrollTo(0, dim.Top);
    
    return false;
}

/**
 * Sajith.m
 * used to focus the div when clicked on the anchor tag on the view page
 */
function focusMostWatchedAds() {
    
    var elem = document.getElementById('divMostWatched');
    var emailMsg = document.getElementById("emailMsgId");
    
    if (emailMsg) {
        emailMsg.style.display = 'none';
    }
    
    /* will not work in IE as ie calculates top relative to the enclosed or 
     * parent component */
    // window.scrollTo(0, document.getElementById('divMostWatched').offsetTop);
    var dim = GetTopLeft(elem);
    
    window.scrollTo(0, dim.Top);
    
    return false;
}

function selectAllCheckboxUsers() {
    var sltAllUsers = document.getElementById("frmManualAlert:sltAllUser");
    
    for (var i = 0; i < document.frmManualAlert.elements.length; i++) {
        var e = document.frmManualAlert.elements[i];        
        
        if (e.type == 'checkbox' && !e.disabled) {  
            e.checked = true;
        //e.click();
        }
        
        
    } // end of for
    
    sltAllUsers.value = true;
    
    return false;
}

/**
 *
 */
function saveSelectedId(chk, endUserId) {
    var sltIdList = document.getElementById("frmManualAlert:sltIdList");
    var selectedAll =  document.getElementById("frmManualAlert:sltAllUser").value;
    // after selecting the values deselected certain values
    var removedValues = document.getElementById("frmManualAlert:dsltValues");
    var hdnUnchecked = document.getElementById("frmManualAlert:hdnSltUnchecked");
    
    if (chk && chk.checked){
        sltIdList.value += "" + endUserId + ",";
        
        if (eval(selectedAll)) {
            var dsltArr = removedValues.value.split(',');
            var j = 0;
            var newRmvList = "";
            
            for ( i = 0; i < dsltArr.length - 1; i++) {
                
                if (parseInt(endUserId) != parseInt(dsltArr[i])) {
                    newRmvList += sltIdArr[i] + ",";
                }
                
            } // end of for loop
            
            removedValues.value = newRmvList;
        }
        
    }else {
        
        if (eval(selectedAll)) {
            document.getElementById("frmManualAlert:dsltAllUser").value = true;
            removedValues.value += "" + endUserId + ",";
        }        
        
        var sltIdArr = sltIdList.value.split(',');
        var i = 0;
        var newIdList = "";
        
        for ( i = 0; i < sltIdArr.length - 1; i++) {
            
            if (parseInt(endUserId) != parseInt(sltIdArr[i])) {
                newIdList += sltIdArr[i] + ",";
            }
            
        } // end of for loop
        //alert("New Id List  :: " + newIdList);
        sltIdList.value = newIdList;
        hdnUnchecked.value += parseInt(endUserId) + ",";
    }
    
//alert(" Id List :: " + sltIdList.value);
} // end of function


function defaultSelectUsers() {
    var selectedAll =  document.getElementById("frmManualAlert:sltAllUser").value;
    //alert(selectedAll);
    
    if (eval(selectedAll) == true) {
        //alert("Inside true");
        selectAllCheckboxUsers();
    } else {
//alert("else");
}
    
} // end of function

/**
 * Retrieve the data table and select the users who is selected as selected.
 *   
 */
function checkSelectedUsers() {
    var table = document.getElementById("frmManualAlert:userList");
    // var selectedAll =  document.getElementById("frmManualAlert:sltAllUser").value;
    var selectedAll =  document.getElementById("frmManualAlert:hdnSendToAll").value;
    var sltIdList = document.getElementById("frmManualAlert:sltIdList");
    var dsltIdList =  document.getElementById("frmManualAlert:dsltValues").value;
    //alert(" Slt Id List :: " + sltIdList.value);
    
    if (table) {
        var rows = table.rows;
        //alert("Rows Length : " + rows.length );
        var i = 0;
        var sltIdArr = sltIdList.value.split(',');
        var dsltIdArr = dsltIdList.split(',');
        
        for (i = 1; i < rows.length; i++) {
            //alert(rows[i].innerHTML);
            var cells = rows[i].cells;
            var childrens = cells[2].childNodes; 
            var hdnEndUserId = childrens[0].value;
            var chk = childrens[1];
            
            
            if (eval(selectedAll) == true) {
                
                if (dsltIdArr.length > 0) {
                    
                    var k = 0;
                    for(k = 0; k < dsltIdArr.length; k++) {
                        
                        if (parseInt(hdnEndUserId) == parseInt(dsltIdArr[k])) {
                            // alert("inside the loop : " + dsltIdArr[k] + "  :: hidden Id :: " + hdnEndUserId);
                            // alert(" Chk : " + chk.type);
                            //alert("inside the == condition" + chk);
                            chk.checked = false;
                        } 
                        
                    } // end of for loop
                    
                } //  end of if condition                  
                
            } else {
                
                if (sltIdArr.length > 0) {
                    
                    //  alert("inside the loop : " + sltIdArr[0] + "  :: hidden Id :: " + hdnEndUserId);
                    var k = 0;
                    for(k = 0; k < sltIdArr.length; k++) {
                        
                        if (parseInt(hdnEndUserId) == parseInt(sltIdArr[k])) {
                            //  alert("inside the == condition");
                            chk.checked = true;
                        }
                        
                    } // end of for loop
                    
                } //  end of if condition                
                
            } // end of else condition
            
        //alert(hdnEndUserId);
        } // end of for loop
        
    } // end outer if condition
    
} // end of function


/**
 * Store already selected values to selected values
 * Sajith.m
 */
function storeAlreadySelected() {
    var idList = document.getElementById("frmManualAlert:alreadySelected");
    var sltIdList = document.getElementById("frmManualAlert:sltIdList");
    var storAlreadySlt = document.getElementById("frmManualAlert:hdnStoreSlt");
    var boolVal = storAlreadySlt.value;
    //alert("Boolean : " + boolVal);
    
    if (eval(boolVal) == false) {
        // need to do this only the first time
        // alert("First time setting all values to sltIdList");
        sltIdList.value = idList.value;
        storAlreadySlt.value = true;
    } else {
//  alert("Inside Else Case");
        
}
    
/**
     if (sltIdList.value.length > 0) {
     } else {
     // need to do this only the first time
     alert("First time setting all values to sltIdList");
     sltIdList.value = idList.value;
     }
     **/
}


/************ added methods **********/
/********added ones *******/
function checkOrUncheckUsers(chk) {
    var sltAllUsers = document.getElementById("frmManualAlert:hdnSendToAll");
    
    for (var i = 0; i < document.frmManualAlert.elements.length; i++) {
        var e = document.frmManualAlert.elements[i];        
        
        if (e.type == 'checkbox' && !e.disabled) {  
            e.checked = chk.checked;
        //e.click();
        }
        
    } // end of for
    
    if (chk.checked) {
        sltAllUsers.value = true;
        document.getElementById("frmManualAlert:hdnUncheckAll").value = false;
        document.getElementById("frmManualAlert:dsltValues").value = "";
        
    }else {
        document.getElementById("frmManualAlert:hdnUncheckAll").value = true;
        dsltIdList =  document.getElementById("frmManualAlert:dsltValues").value = "";
        //document.getElementById("frmManualAlert:alreadySelected").value = "";
        document.getElementById("frmManualAlert:sltIdList").value = "";
        
        sltAllUsers.value = false;
    }
    
}

function checkUsers() {
    
    for (var i = 0; i < document.frmManualAlert.elements.length; i++) {
        var e = document.frmManualAlert.elements[i];        
        
        if (e.type == 'checkbox' && !e.disabled) {  
            e.checked = true;
        }
        
    } // end of for
    
}

function unCheckUsers() {
    
    for (var i = 0; i < document.frmManualAlert.elements.length; i++) {
        var e = document.frmManualAlert.elements[i];        
        
        if (e.type == 'checkbox' && !e.disabled) {  
            e.checked = false;
        }
        
    } // end of for
    
}
/** Function to set company address as billing address
 * Shreeja Ravindranathan
 * 28.08.09
 */
function fnSetBillingAddressAsCompanyAddress(booleanBillingAddressSameAsCompanyAddress) {
    if (true == booleanBillingAddressSameAsCompanyAddress) {
        document.getElementById("frmContact:txtAddressLine1").value = document.getElementById("frmContact:hdnAddressLine1").value;
        document.getElementById("frmContact:txtAddressLine2").value = document.getElementById("frmContact:hdnAddressLine2").value;
        document.getElementById("frmContact:txtCity").value = document.getElementById("frmContact:hdnCity").value;
        document.getElementById("frmContact:smnuState").value = document.getElementById("frmContact:hdnState").value;
        document.getElementById("frmContact:ZipCode").value = document.getElementById("frmContact:hdnZipCode").value;
    } else {
        document.getElementById("frmContact:txtAddressLine1").value = "";
        document.getElementById("frmContact:txtAddressLine2").value = "";
        document.getElementById("frmContact:txtCity").value = "";
        document.getElementById("frmContact:smnuState").value = "None";
        document.getElementById("frmContact:ZipCode").value = "";
    }
}
function defaultSelection() {
    var selectedAll =  document.getElementById("frmManualAlert:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("frmManualAlert:dsltValues").value;
    //alert(selectedAll);
    
    if (eval(selectedAll) == true) {
        //alert("Inside true");
        checkUsers();
    } else {
        unCheckUsers();
    }
    
}

function storeSelected(chk, endUserId) {
    var sltIdList = document.getElementById("frmManualAlert:sltIdList");    
    var chkAll =  document.getElementById("frmManualAlert:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("frmManualAlert:dsltValues");
    
    if (chk && chk.checked) {
        sltIdList.value += endUserId + ",";
        
        if (eval(chkAll) == true) {
            var dsltArr = dsltIdList.value.split(",");
            var dsltVal = "";
            
            for (var j = 0; j < dsltArr.length - 1; j++) {
                
                if (parseInt(endUserId) != parseInt(dsltArr[j])) {
                    dsltVal += dsltArr[j] + ",";
                } // end of for loop
                
            } // end of for loop
            
            // remove from already selected list
            
            
            
            // give new value to the deselected values
            dsltIdList.value = dsltVal;
        } // end of if condition
        
    } else {
        var sltArr = sltIdList.value.split(",");
        var newValue = "";
        
        for (var i = 0; i < sltArr.length - 1; i++) {
            
            if (parseInt(endUserId) != parseInt(sltArr[i])) {
                newValue += sltArr[i] + ",";
            } // end of if condition
            
        } // end of for loop
        
        sltIdList.value = newValue;
        
        if (eval(chkAll) == true) {
            dsltIdList.value += endUserId + ",";
        } else {
    }
        
        
    } // end of else condition
    
//  alert("Removal List : " + dsltIdList.value);
//  alert("Values Are : " + sltIdList.value);
}


//Methods from createAd.jsp page

function clearInput(obj) {
    try{
        var parentElement = obj.parentNode;
        parentElement.innerHTML = parentElement.innerHTML;
    }catch(e) {
        alert(e.message);
    }
}
//Validate Coupon Expiry Date
function validateCouponExpiryDate() {
    var couponTypes = document.frmCreateAd["frmCreateAd:rdoCoupon"];
    var origCouponTypeId = document.getElementById("hiddenTypeId").value;    

    if (!validateAllDateFields()) {
        return false;
    }
    
    if (!couponTypes[0].checked && origCouponTypeId != 0) {
        document.getElementById('frmCreateAd:CouponExpiryDate'+'.day').value = '';
        document.getElementById('frmCreateAd:CouponExpiryDate'+'.month').value = '-1';
        document.getElementById('frmCreateAd:CouponExpiryDate'+'.year').value = '';
    }

    if (!couponTypes[1].checked && origCouponTypeId != 1) {

        document.getElementById('frmCreateAd:dynamicCouponCouponExpiryDate'+'.day').value = '';
        document.getElementById('frmCreateAd:dynamicCouponCouponExpiryDate'+'.month').value = '-1';
        document.getElementById('frmCreateAd:dynamicCouponCouponExpiryDate'+'.year').value = '';
    }

    var couponDay;
    var couponMonth;
    var couponYear;

    if (couponTypes[0].checked) {
        couponDay = document.getElementById('frmCreateAd:CouponExpiryDate'+'.day').value;
        couponMonth = document.getElementById('frmCreateAd:CouponExpiryDate'+'.month').value;
        couponYear = document.getElementById('frmCreateAd:CouponExpiryDate'+'.year').value;
    } else {
        couponDay = document.getElementById('frmCreateAd:dynamicCouponCouponExpiryDate'+'.day').value;
        couponMonth = document.getElementById('frmCreateAd:dynamicCouponCouponExpiryDate'+'.month').value;
        couponYear = document.getElementById('frmCreateAd:dynamicCouponCouponExpiryDate'+'.year').value;
    }
    if (couponDay != '' && couponMonth != -1 && couponYear != '' ) {
        var couponExpiryDate = new Date(couponYear,couponMonth,couponDay);

        var adDay = document.getElementById('frmCreateAd:EndDate'+'.day').value;
        var adMonth = document.getElementById('frmCreateAd:EndDate'+'.month').value;
        var adYear = document.getElementById('frmCreateAd:EndDate'+'.year').value;
        var adEndDate = new Date(adYear,adMonth,adDay);
        if (couponExpiryDate < adEndDate) {
            if(!(confirm('The coupon expiry date is before the ad end date. Are you sure to proceed with this?'))) return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
    
}

/**
 * validates all dates fields in Ad Portal: Create Ad & Edit Ad
 */
function validateAllDateFields() {

    if (!validateDateIfFilled("frmCreateAd:StartDate")
        | !validateDateIfFilled("frmCreateAd:EndDate")
        | !validateDateIfFilled("frmCreateAd:CouponExpiryDate")
        | !validateDateIfFilled("frmCreateAd:dynamicCouponCouponExpiryDate")) {
        return false;
    }
    return true;
}

/**
 * validates dateElement If filled
 */
function validateDateIfFilled(dateElement) {

    if ((null == document.getElementById(dateElement))
        || (null == document.getElementById(dateElement + ".day"))
        || (null == document.getElementById(dateElement + ".month"))
        || (null == document.getElementById(dateElement + ".year"))) {
        return true;
    }
    var dayfield = document.getElementById(dateElement + ".day").value;
    var monthfield = document.getElementById(dateElement + ".month").value;
    var yearfield = document.getElementById(dateElement + ".year").value;
    var validDate = true;

    if (null != document.getElementById("dynDateErrId").innerHTML) {
        document.getElementById("dynDateErrId").innerHTML = '';
    }

    if (null != document.getElementById("staticDateErrId").innerHTML) {
        document.getElementById("staticDateErrId").innerHTML = '';
    }

    // removes previous error message if exists
    if (null != document.getElementById(dateElement + ".errorMesg")) {
        document.getElementById(dateElement).removeChild(
            document.getElementById(dateElement + ".errorMesg"));
    }
    
    if((dayfield == '') && (monthfield == -1) && (yearfield== '')) {
        validDate = true;
    }else if ((dayfield == '') || (monthfield == -1) || (yearfield== '')) {
        validDate = false;
    } else {
        var dayobj = new Date(yearfield, monthfield-1, dayfield);
        if ((dayobj.getMonth()+1 != monthfield)||(dayobj.getDate()!= dayfield)
            ||(dayobj.getFullYear()!= yearfield)) {
            validDate = false;
        }
    }

    // adds errormesg if date not valid
    if(!validDate) {
        var errorMesg = document.createElement("span");
        errorMesg.id = dateElement + ".errorMesg";
        errorMesg.innerHTML = "The given value is not a correct date.";
        errorMesg.className = "errordynamic";
        document.getElementById(dateElement).appendChild(errorMesg);
        document.getElementById(dateElement + ".day").focus();
    }
    return validDate;
}

//Method from adminHome.jsp -- Begin
function callFun(){
    //alert('hai');
    var e = document.getElementById('leftMenuId');
    //  alert(e);
    e.style.display='none';
}
//Method from adminHome.jsp -- End


//Method from feedback.jsp -- Begin
function makeUserNameAnonymous(){
}
//Method from feedback.jsp -- End

//Method from fingerprintVerification.jsp -- Begin
function disableLink(b) {
    //alert(b.value);
    //b.disabled = true;
    document.getElementById('fingerPrintId:linkId1').style.display = 'none';
    document.getElementById('fingerPrintId:linkId2').style.display = 'block';
    return true;
}

function disableLink1(b)
{
    // alert('NEW BUTTON');
    return false;
}

//Method from fingerprintVerification.jsp -- End

//Methods from alertParameter.jsp -- Begin
function selectAllCheckboxDynAlert(chk) {

    for (var i = 0; i < document.frmAlertParameter.elements.length; i++) {
        var e = document.frmAlertParameter.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = chk.checked;
        }
    }
}

function uncheckMasterCheckBoxDynAlert() {

    var fom = document.getElementById('frmAlertParameter:modifyAll')
    var incr = 0;
    var total = 0;
    for (var i = 0; i < document.frmAlertParameter.elements.length; i++) {
        var e = document.frmAlertParameter.elements[i];

        if (e.type == 'checkbox' && e.name != 'frmAlertParameter:modifyAll') {
            total = total + 1;
            if (e.checked){
                incr = incr + 1;
            }
        }
    }

    if (total == incr){
        fom.checked = true;
    } else {
        fom.checked = false;
    }
}

//Methods from alertParameter.jsp -- End

//Method from createParentCampaign.jsp -- Begin
function ValidateForm(){
    
    var startDateDayObj = document.getElementById("parentCampaignId:startDate"+'.day');
    startDateDayObj.value ='';
    var startDateMonthObj = document.getElementById("parentCampaignId:startDate"+'.month');
    startDateMonthObj.value = -1;
    var startDateYearObj = document.getElementById("parentCampaignId:startDate"+'.year');
    startDateYearObj.value = '';
    var endDateDayObj = document.getElementById("parentCampaignId:endDate"+'.day');
    endDateDayObj.value = '';
    var endDateMonthObj = document.getElementById("parentCampaignId:endDate"+'.month');
    endDateMonthObj.value = -1;
    var endDateYearObj = document.getElementById("parentCampaignId:endDate"+'.year');
    endDateYearObj.value = '';
}

//Method from createParentCampaign.jsp -- Begin

//Method from myNetwork.jsp -- Begin
function showExceedMessage(show, message) {
    if(show == 1) {
        /* alert("You exceeds your Initial referral limit. You can continue " +
        "referring only if any of your referrees not accepting your request" +
        " within allowed time.");*/
        alert(message);
    }else {
        return true;
    }
    return false;
}

//Method from myNetwork.jsp -- End

//Method from userDetailsView.jsp -- Begin
function allow_numeric_value(obj,e){
    nn=(document.layers)?true:false;
    ie=(document.all)?true:false;
    var evt=(e)?e:(window.event)?window.event:null;
    if(evt) {
        var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));

        if(key == "37") {
            return true;
        }
    }
    if (/[^+0-9]/i.test(obj.value))
        obj.value=obj.value.replace(/[^+0-9]/g,'')
    obj.value+=''
    obj.focus()
}

//Method from userDetailsView.jsp -- End

//Method from campaignApprovalDetail.jsp -- Begin
function checkDynSelection(obj) {
    try{
        if (obj.checked == 1) {
            return;
        } else {

            var id = obj.id;
            id = id.replace(/chk_UserType/, "options");
            var sltObj = document.getElementById(id);

            if(null != sltObj) {
                for(var i = 0; i < sltObj.options.length; i++) {
                    sltObj.options[i].selected = false;
                }
            }
        }
    }catch(e) {
        alert(e.message)
    }
}

//Method from campaignApprovalDetail.jsp -- End

//Method from questionEdit.jsp -- Begin
function checkDynSelectionQnEdit(obj) {
    try{
        if (obj.checked == 1) {
            return;
        } else {

            var id = obj.id;
            id = id.replace(/chk_UserType/, "options");
            var sltObj = document.getElementById(id);

            if(null != sltObj) {
                for(var i = 0; i < sltObj.options.length; i++) {
                    sltObj.options[i].selected = false;
                }
            }
        }
    }catch(e) {
        alert(e.message)
    }
}

//Method from questionEdit.jsp -- End

//Method from manageMostWatchedAdsList.jsp -- Begin
function checkOrUncheckAllAd(chk) {
    
    var sltAllAds = document.getElementById("mostWatchedAdsReport:hdnSendToAll");

    for (var i = 0; i < document.mostWatchedAdsReport.elements.length; i++) {
        var e = document.mostWatchedAdsReport.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = chk.checked;
        //e.click();
        }

    } // end of for

    if (chk.checked) {
        sltAllAds.value = true;
        document.getElementById("mostWatchedAdsReport:hdnUncheckAll").value = false;
        document.getElementById("mostWatchedAdsReport:dsltValues").value = "";
    } else {
        document.getElementById("mostWatchedAdsReport:hdnUncheckAll").value = true;
        dsltIdList =  document.getElementById("mostWatchedAdsReport:dsltValues").value = "";
        //document.getElementById("mostWatchedAdsReport:alreadySelected").value = "";
        document.getElementById("mostWatchedAdsReport:sltIdList").value = "";

        sltAllAds.value = false;
    }
}

// Storing values when check all option is selected
function defaultSelections() {
    var selectedAll =  document.getElementById("mostWatchedAdsReport:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("mostWatchedAdsReport:dsltValues").value;
    //alert(selectedAll);

    if (eval(selectedAll) == true) {
        //alert("Inside true");
        checkAd();
    }else {
        unCheckAd();
    }
}

function checkAd() {

    for (var i = 0; i < document.mostWatchedAdsReport.elements.length; i++) {
        var e = document.mostWatchedAdsReport.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = true;
        }
    } // end of for
}

function unCheckAd() {

    for (var i = 0; i < document.mostWatchedAdsReport.elements.length; i++) {
        var e = document.mostWatchedAdsReport.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = false;
        }
    } // end of for
}

// Storing values already selected if navigated through different pages
function checkAllSelectedAds() {

    var table = document.getElementById("mostWatchedAdsReport:tblMostWatchedAds");
    var idList = document.getElementById("mostWatchedAdsReport:alreadySelected");
    // var selectedAll =  document.getElementById("mostWatchedAdsReport:sltAllUser").value;
    var selectedAll =  document.getElementById("mostWatchedAdsReport:hdnSendToAll").value;
    var sltIdList = document.getElementById("mostWatchedAdsReport:sltIdList");
    var dsltIdList =  document.getElementById("mostWatchedAdsReport:dsltValues").value;

    if (table) {
        var rows = table.rows;
        //alert("Rows Length : " + rows.length );
        var i = 0;
        var sltIdArr = idList.value.split(',');
        //alert('Array------>' + sltIdArr);
        var dsltIdArr = dsltIdList.split(',');

        for (i = 1; i < rows.length; i++) {
            //alert(rows[i].innerHTML);
            var cells = rows[i].cells;

            var childrens = cells[0].childNodes;

            var hdncampaignId = childrens[0].value;
            var chk = childrens[1];
            // alert(hdncampaignId);

            if (eval(selectedAll) == true) {

                if (dsltIdArr.length > 0) {

                    var k = 0;
                    for(k = 0; k < dsltIdArr.length; k++) {

                        if (parseInt(hdncampaignId) == parseInt(dsltIdArr[k])) {
                            // alert("inside the loop : " + dsltIdArr[k] + "  :: hidden Id :: " + hdncampaignId);
                            // alert(" Chk : " + chk.type);
                            //alert("inside the == condition" + chk);
                            chk.checked = false;
                        }

                    } // end of for loop

                } //  end of if condition

            }else {

                if (sltIdArr.length > 0) {
                    //alert(sltIdArr[0]);
                    //  alert("inside the loop : " + sltIdArr[0] + "  :: hidden Id :: " + hdncampaignId);
                    var k = 0;
                    for(k = 0; k < sltIdArr.length; k++) {
                        // alert('Length ' + k + ' ' + sltIdArr[k] + ' campaignid----' + hdncampaignId);
                        if (parseInt(hdncampaignId) == parseInt(sltIdArr[k])) {
                            //alert("inside the == condition");
                            chk.checked = true;
                        }

                    } // end of for loop

                } //  end of if condition

            } // end of else condition

        //alert(hdncampaignId);
        } // end of for loop

    } // end outer if condition

} // end of function

// Storing values when individual check boxes are checked in datatable

function storeSelectedCheckAds(chk, campaignId) {
    var sltIdList = document.getElementById("mostWatchedAdsReport:sltIdList");
    var chkAll =  document.getElementById("mostWatchedAdsReport:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("mostWatchedAdsReport:dsltValues");

    if (chk && chk.checked) {

        sltIdList.value += campaignId + ",";
        if (eval(chkAll) == true) {
            var dsltArr = dsltIdList.value.split(",");
            var dsltVal = "";

            for (var j = 0; j < dsltArr.length - 1; j++) {

                if (parseInt(campaignId) != parseInt(dsltArr[j])) {
                    dsltVal += dsltArr[j] + ",";
                } // end of for loop

            } // end of for loop

            // remove from already selected list



            // give new value to the deselected values
            dsltIdList.value = dsltVal;
        } // end of if condition

    }else {


        var sltArr = sltIdList.value.split(",");
        var newValue = "";

        for (var i = 0; i < sltArr.length - 1; i++) {

            if (parseInt(campaignId) != parseInt(sltArr[i])) {
                newValue += sltArr[i] + ",";
            } // end of if condition

        } // end of for loop

        sltIdList.value = newValue;

        if (eval(chkAll) == true) {
            dsltIdList.value += campaignId + ",";
        }else {
    }
    } // end of else condition
}

function storeAlreadySelectedAds() {

    var idList = document.getElementById("mostWatchedAdsReport:alreadySelected");
    var sltIdList = document.getElementById("mostWatchedAdsReport:sltIdList");
    var storAlreadySlt = document.getElementById("mostWatchedAdsReport:hdnStoreSlt");

    var boolVal = storAlreadySlt.value;
    //alert("Boolean : " + eval(boolVal));

    if (eval(boolVal) == false) {

        // need to do this only the first time
        // alert("First time setting all values to sltIdList");
        // alert("Values : " + idList.value);
        sltIdList.value = idList.value;
        storAlreadySlt.value = true;

    } else {
//alert("Inside Else Case");


}

/**
     if (sltIdList.value.length > 0) {
     } else {
     // need to do this only the first time
     //alert("First time setting all values to sltIdList");
     sltIdList.value = idList.value;
     }
     **/
}
//Method from manageMostWatchedAdsList.jsp -- End

//Method from advCampaignReportListView.jsp -- Begin
function showSearchOption() {
    
    document.getElementById("searchDiv").style.display = "block";
    //$("#searchDiv").hide("slow");

    document.getElementById("searchOption").style.display = "none";
    document.getElementById("hideOption").style.display = "block";
//document.getElementById("advRegForm:searchOption").setAttribute("rendered", false);
}
function hideSearchOption() {
    document.getElementById("searchDiv").style.display = "none";
    //$("#searchDiv").show("slow");
    document.getElementById("searchOption").style.display = "block";
    document.getElementById("hideOption").style.display = "none";
//document.getElementById("advRegForm:hideOption").setAttribute("rendered", false);
}

//Method from advCampaignReportListView.jsp -- End

//Method from adQuestionsAdd.jsp -- Begin
function DisableButton(b)
{
    //alert(b.value);
    //b.disabled = true;
    document.getElementById('frmAddQuestion:group1').style.display = 'none';
    document.getElementById('frmAddQuestion:group2').style.display = 'block';
    return true;

}

function DisableButton1(b)
{
    // alert('NEW BUTTON');
    return false;

}
//Method from adQuestionsAdd.jsp -- End

//Method from campaignPublish.jsp - Begin
function getHttpObject() {
    var xmlHttp = null;
    try{
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }catch (e) {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    return xmlHttp;
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

var previewInterval = 0; // used in Ad Portal -- create\edit Ad & Manage Most Viewed Ads

/**
 * Stores template-id & provider-url in database and calls coupon preview
 * Used Ad Portal - Create Ad & Edit Ad
 *
 */
function updateCouponPreview() {
    try {
        var xmlHttp = getHttpObject();
        var userId = document.getElementById("userId").value;
        var updateUrl = "advCouponPreviewUpdate.jsf";
        var templates = document.frmCreateAd["frmCreateAd:templRadio"];
        var templateId;

        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {

                var updateStatus = xmlHttp.responseText;
                
                if (updateStatus.indexOf("success") >= 0) {
                    getCouponPreview();
                    couponPopup(1);
                    previewInterval = setInterval('getCouponPreview()', 30000);
                }
            }
        } // end of function

        for (i=0; i<templates.length; i++) {

            if (templates[i].checked == true) {
                templateId = templates[i].value;
                break;
            }
        } // end of for

        updateUrl += "?templateId=" + templateId;
        updateUrl += "&providerId=" + document.frmCreateAd["frmCreateAd:smnuProviderList"].value;

        var paramStr = document.getElementById("providerParameters").value;
        var reqParamStr = document.getElementById("requiredParams").value;
        var paramArr = paramStr.split(",");

        for (var i=0; i < paramArr.length; i++) {

            if (reqParamStr.indexOf(paramArr[i]) >= 0) {

                var paramVal = document.getElementById(paramArr[i]).value;

                if( paramVal.trim() == "") {
                    alert("Please fill in all mandatory fields of Coupon");
                    return false;
                }
            } // end of if

            updateUrl += "&" + paramArr[i] + "=" + paramVal;
        } // end of for
        
        xmlHttp.open("GET",updateUrl,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }
}

/**
 * Displays the Coupon Preview when the image is created by scheduler
 * else it displays a loading image. In case of error, it displays error mesg.
 * Used Ad Portal - Create Ad & Edit Ad
 *
 */
function getCouponPreview() {
    
    var userId = document.getElementById("userId").value;
    try{
        var xmlHttp = getHttpObject();

        var url = "couponPreview.do?userId="+userId;

        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {
                var imageFound = xmlHttp.getResponseHeader("imageFound");
                var errorMesg = xmlHttp.getResponseHeader("errorMesg");

                var imgDiv = document.getElementById("imgDiv");
                var mesgDiv = document.getElementById("mesgDiv");
                var loadingImg = document.getElementById("loadingImg");

                if (imageFound == 1) { // if image found, displays image

                    var now = new Date();

                    imgDiv.innerHTML = ""; // to remove old images
                    var newimage = document.createElement('img');
                    newimage.setAttribute("src", url + "&time=" + now.getTime());
                    newimage.setAttribute("id", "img1");
                    imgDiv.appendChild(newimage);

                    imgDiv.style.visibility = "visible";
                    imgDiv.style.display = "";
                    loadingImg.style.visibility = "hidden";
                    loadingImg.style.display = "none";
                    mesgDiv.style.visibility = "hidden";
                    mesgDiv.style.display = "none";

                    clearInterval(previewInterval);
                    
                } else if ((null != errorMesg) && ("null" != errorMesg) && ("" != errorMesg)) {
                    // in case of error, displays error mesg
                    
                    imgDiv.innerHTML =
                    "<p style='margin-top:20px;margin-left:20px;color:red;'>"
                    + "Coupon Generation failed due to the following reason:"
                    + "<br><br>" + errorMesg + "</p>";

                    imgDiv.style.visibility = "visible";
                    imgDiv.style.display = "";
                    
                    loadingImg.style.visibility = "hidden";
                    loadingImg.style.display = "none";
                    mesgDiv.style.visibility = "hidden";
                    mesgDiv.style.display = "none";

                    clearInterval(previewInterval);

                }else { // image not found & no error mesg, displays loading...
                    
                    imgDiv.style.visibility = "hidden";
                    imgDiv.style.display = "none";
                    loadingImg.style.visibility = "visible";
                    loadingImg.style.display = "";
                    mesgDiv.style.visibility = "visible";
                    mesgDiv.style.display = "";
                }
            }
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }
}

/**
 * The following variable 'selectedPartnerIds' is used in
 * updateCouponPreviewFromAdmin() & getCouponPreviewForAdmin()
 */
var selectedPartnerIds = ""; 

/**
 * Stores template-id & provider-url in database and calls coupon preview
 * Used Ad Portal - Create Ad & Edit Ad
 *
 */
function updateCouponPreviewFromAdmin() {
    try {
        var xmlHttp = getHttpObject();
        var userId = document.getElementById("userId").value;
        var updateUrl = "advCouponPreviewUpdate.jsf";
        var templates = document.editCampaignDetails["editCampaignDetails:templRadio"];
        var templateId;

        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {
                
                var updateStatus = xmlHttp.responseText;
                
                if (updateStatus.indexOf("success") >= 0) {

                    selectedPartnerIds = xmlHttp.getResponseHeader("partnerIds");
                    
                    getCouponPreviewForAdmin();
                    couponPopup(1);
                    previewInterval = setInterval('getCouponPreviewForAdmin()', 30000);
                }
            }
        } // end of function

        for (i=0; i<templates.length; i++) {

            if (templates[i].checked == true) {
                templateId = templates[i].value;
                break;
            }
        } // end of for

        updateUrl += "?templateId=" + templateId;
        updateUrl += "&regionId=" + document.getElementById("regionId").value
        updateUrl += "&campaignId=" + document.getElementById("campaignId").value;
        updateUrl += "&providerId=" + document.editCampaignDetails["editCampaignDetails:smnuProviderList"].value;
        


        var paramStr = document.getElementById("parameters").value;
        var reqParamStr = document.getElementById("requiredParams").value;
        var paramArr = paramStr.split(",");

        for (var i=0; i < paramArr.length; i++) {

            if (reqParamStr.indexOf(paramArr[i]) >= 0) { // if param is required

                var paramVal = document.getElementById(paramArr[i]).value;

                if( paramVal.trim() == "") {
                    alert("Please fill in all mandatory fields of Coupon");
                    return false;
                }
            } // end of if

            updateUrl += "&" + paramArr[i] + "=" + paramVal;
        } // end of for
        
        xmlHttp.open("GET",updateUrl,true);
        xmlHttp.send(null);
         
    }catch(e){
        alert(e.message);
    }
    
}

/**
 * Displays the Coupon Preview when the image is created by scheduler
 * else it displays a loading image. In case of error, error-mesg is displayed.
 * Used in Manage Most Viewed Ads
 *
 */
function getCouponPreviewForAdmin() {

    var userId = document.getElementById("userId").value;
    try{
        var xmlHttp = getHttpObject();

        var url = "couponPreview.do?userId="+userId;
        
        var partnerList = selectedPartnerIds.split(",");
        
        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {
                var imageFound = xmlHttp.getResponseHeader("imageFound");
                var errorMesg = xmlHttp.getResponseHeader("errorMesg");

                var imgDiv = document.getElementById("imgDiv");
                var mesgDiv = document.getElementById("mesgDiv");
                var loadingImg = document.getElementById("loadingImg");

                if (imageFound == 1) { // if image found, displays image
                    
                    var now = new Date();
                    imgDiv.innerHTML = ""; // to remove old images
                    
                    for(var i=0; i < partnerList.length; i++) {
                        
                        var newimage = document.createElement('img');
                        newimage.setAttribute("src", url + "&partnerId="+partnerList[i]+"&time="+now.getTime());
                        newimage.setAttribute("id", "img"+i);

                        if (!newimage.complete) {
                            newimage.setAttribute("src", url + "&partnerId="
                                +partnerList[i]+"&time="+ (new Date()).getTime());
                        }
                        imgDiv.appendChild(newimage);

                        var linebreak1 = document.createElement('br');
                        imgDiv.appendChild(linebreak1);
                        var linebreak2 = document.createElement('br');
                        imgDiv.appendChild(linebreak2);
                    } // end of for
                     
                    imgDiv.style.visibility = "visible";
                    imgDiv.style.display = "";
                    loadingImg.style.visibility = "hidden";
                    loadingImg.style.display = "none";
                    mesgDiv.style.visibility = "hidden";
                    mesgDiv.style.display = "none";

                    clearInterval(previewInterval);

                } else if ((null != errorMesg) && ("null" != errorMesg) && ("" != errorMesg)) {
                    // in case of error, displays error
                    imgDiv.innerHTML =
                    "<p style='margin-top:20px;margin-left:10px;color:red;'>"
                    + "Coupon Generation failed due to the following reason:"
                    + "<br><br>" + errorMesg + "</p>";
                    
                    imgDiv.style.visibility = "visible";
                    imgDiv.style.display = "";
                    
                    loadingImg.style.visibility = "hidden";
                    loadingImg.style.display = "none";
                    mesgDiv.style.visibility = "hidden";
                    mesgDiv.style.display = "none";

                    clearInterval(previewInterval);
                    
                }else { // image not found & no error mesg, displays loading...
                    
                    imgDiv.style.visibility = "hidden";
                    imgDiv.style.display = "none";
                    loadingImg.style.visibility = "visible";
                    loadingImg.style.display = "";
                    mesgDiv.style.visibility = "visible";
                    mesgDiv.style.display = "";
                }
            }
        }// end of function
        
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }
}

function showBackgroundRepeat(val) {
    if (null != val) {
        document.getElementById("frmPartnerList:lblBackGroundRepeatText").style.display='';
        document.getElementById("frmPartnerList:lblBackGroundRepeat").style.display='';
    }else {
        document.getElementById("frmPartnerList:lblBackGroundRepeatText").style.display='none';
        document.getElementById("frmPartnerList:lblBackGroundRepeat").style.display='none';
    }
}

function buildPartnerUrl() {

    var url = document.getElementById("frmPartnerList:hdnRequestUrl").value;
    var campaignsource = document.getElementById("frmPartnerList:txtCampaignSource").value;
    var campaignmedium = document.getElementById("frmPartnerList:txtCampaignMedium").value;
    var campaignterm = document.getElementById("frmPartnerList:txtCampaignTerm").value;
    var campaigncontent = document.getElementById("frmPartnerList:txtCampaignContent").value;
    var campaignname = document.getElementById("frmPartnerList:txtCampaignName").value;

    if (null != url) {
        url = appendToPartnerUrl(url,"utm_source",encodeURIComponent(campaignsource));
        url = appendToPartnerUrl(url,"&utm_medium",encodeURIComponent(campaignmedium));
        url = appendToPartnerUrl(url,"&utm_term",encodeURIComponent(campaignterm));
        url = appendToPartnerUrl(url,"&utm_content",encodeURIComponent(campaigncontent));
        url = appendToPartnerUrl(url,"&utm_campaign",encodeURIComponent(campaignname));
        //   document.getElementById("frmPartnerList:hdnRequestUrl").value = url;
        document.getElementById("frmPartnerList:hdnPartnerUrl").value = url;
        document.getElementById("frmPartnerList:txtPartnerUrl").value = url;
    }
}

function encode(str) {
    var result = "";

    for (i = 0; i < str.length; i++) {
        if (str.charAt(i) == " ") result += "+";
        else result += str.charAt(i);
    }

    str= escape(result);
    return str;
}


function appendToPartnerUrl(url,paramName,paramValue){
    if (null == paramValue) {
        paramValue = "";
    }
    url = url + paramName + "=" +paramValue;
    return url;
}
var timePreviewInterval = 0; // used in publish Ad

function displayGeneratedCoupon() {
    try {
        var xmlHttp = getHttpObject();
        var couponId = document.getElementById('frmDynamicCouponPreview:hidCouponId').value;
        var checkUrl = "checkCouponAjax.jsf";
        //    alert("inside display coupon");

        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {

                var response = xmlHttp.responseText;
                var errorMesg = xmlHttp.getResponseHeader("errorMesg");
                var imgDiv = document.getElementById('frmDynamicCouponPreview:id2');

                if (response == 1) {
                    showCouponPreview();
                    checkUrl="dynamicCouponPreview.jsf";
                    
                } else if ((null != errorMesg) && ("null" != errorMesg) && ("" != errorMesg)) {
                    // in case of error, displays error
                    imgDiv.innerHTML =
                    "<p style='margin-top:20px;margin-left:10px;color:red;font-size:smaller;font-weight:bold;'>"
                    + "Coupon Generation failed due to the following reason:"
                    + "<br><br>" + errorMesg + "</p>";

                    imgDiv.style.display = 'block';

                    document.getElementById('frmDynamicCouponPreview:id3').style.display = 'none';
                    document.getElementById('frmDynamicCouponPreview:id1').style.display = 'none';
                    document.getElementById('backDiv').style.display = 'block';
                    

                    clearInterval(timePreviewInterval);

                }else { // image not found & no error mesg, displays loading...
                    
                    timePreviewInterval = setInterval('displayGeneratedCoupon()', 60000);

                }
            }
        } // end of function

        checkUrl += "?couponid=" + couponId;
        xmlHttp.open("GET",checkUrl,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }
}


/**
 * Displays the Coupon Preview when the image is created by scheduler
 * else it displays a loading image. used in publish manager - generate coupon
 *
 */
function showCouponPreview() {
    //alert("inside showCouponPreview()");
    try{
        var xmlHttp = getHttpObject();

        var campaignId = document.getElementById('frmDynamicCouponPreview:hidCampaignId').value;
        var partnerlist = null;


        var now = new Date();
        var url = "couponthumbnail.do?enduser_id=0&region_id=0&file_type=large&request_type=publish_coupon_preview&cmp_id="+campaignId;
        var url1 = "couponthumbnail.do?enduser_id=0&region_id=0&file_type=large&request_type=publish_coupon_preview&cmp_id="+campaignId;
     

        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {
                var length  = xmlHttp.getResponseHeader("image-length");
                partnerlist = xmlHttp.getResponseHeader("partners");
                //   alert("image-length = "+length);
                //    alert("partners"+xmlHttp.getResponseHeader("partners"));
                if (length == 1) {
                    var divid2 = document.getElementById('frmDynamicCouponPreview:id2');
                    
                    divid2.style.display = 'block';

                    //divid2.innerHTML = "";
                    document.getElementById('frmDynamicCouponPreview:id3').style.display = 'block';
                    document.getElementById('frmDynamicCouponPreview:id1').style.display = 'none';

                    if (null != partnerlist) {

                        var partnerId = partnerlist.split(",");

                        if (partnerId.length > 0) {
                            //     alert("p0"+partnerId[0]+"gg");
                            //  alert("partnerid=" +partnerId[0]);
                            url = url +"&partner_id="+partnerId[0]+"&time="+now.getTime();
                        }
                    
                        if (partnerId.length > 0) {

                            divid2.innerHTML = "";

                            for (i = 0;i < partnerId.length;i++) {
                                var newimage = document.createElement('img');
                                newimage.setAttribute("src", url1 + "&partner_id="+partnerId[i]+"&time="+(new Date()).getTime());
                                newimage.setAttribute("id", "img"+i);
                                
                                if (!newimage.complete) {
                                    newimage.setAttribute("src", url1 + "&partner_id="+partnerId[i]+"&time="+ (new Date()).getTime());
                                }
                                divid2.appendChild(newimage);
                                var linebreak1 = document.createElement('br');
                                divid2.appendChild(linebreak1);
                                var linebreak2 = document.createElement('br');
                               
                                divid2.appendChild(linebreak2);
                            }
                        }
                    }
                    clearInterval(timePreviewInterval);
                //       timePreviewInterval = 0;
                }
                xmlHttp = null;
            // alert("failure"+length);
            }
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }

    return false;
}


function HideContent() {
document.getElementById("popuup_div").style.display = "none";
}

function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}

function showAnsweredUsersCount(parent,questionId)
{
    try{
        var xmlHttp = getHttpObject();

        var url = "answeredUsersAjax.jsp?questionId="+questionId;
        var now = new Date();

        url += "&time=" + now.getTime();

        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {
                var data = xmlHttp.responseText;
                var popupDiv =  document.getElementById("popuup_div");
                document.getElementById("noOfAnsweredUsers").innerHTML = data;
                popupDiv.style.display = "block";
                var placement = findPos(parent);
                popupDiv.style.left = placement[0] + "px";
                popupDiv.style.top = placement[1] + "px";
                //setTimeout("HideContent()", 5000);
                xmlHttp = null;
            }

        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }

    return false;
}
/**
     * coupon preview popup used in Ad portal - create AD & Edit Ad
     *
     */
function couponPopup(sw) {

    var bkDiv = document.getElementById('blackout');
    var popDiv = document.getElementById('divpopup');

    if (sw == 1) {
        // Show popup
       
        bkDiv.style.width = pageWidth() + "px";

        if ( document.body.scrollHeight > screen.height ) {
            bkDiv.style.height = document.body.scrollHeight + "px";
        } else {
            bkDiv.style.height = screen.height + "px";
        }
        bkDiv.style.visibility = 'visible';
        popDiv.style.visibility = 'visible';
        bkDiv.style.display = 'block';
        popDiv.style.display = 'block';
        scroll(0, 0);

    } else {
        // Hide popup
        bkDiv.style.visibility = 'hidden';
        popDiv.style.visibility = 'hidden';
        bkDiv.style.display = 'none';
        popDiv.style.display = 'none';
        clearInterval(previewInterval);
    }

    if (null != document.getElementById("homepageFlash") && null != document.getElementById("divflash") && sw == 0) {
        document.getElementById("homepageFlash").style.display='block';
        document.getElementById("homepageFlash").visibility='visible';
        document.getElementById("divflash").style.display='block';
        document.getElementById("divflash").visibility='visible';
    }

}
        
function testtimeout()
{
    // alert(document.getElementById('hidVideoId').value);
    var videoid = document.getElementById('hidVideoId').value;
    try{
        var xmlHttp = getHttpObject();

        var url = "checkStatusAjax.jsp?videoid="+videoid;
        //alert(url);
        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {
                var data = xmlHttp.responseText;
                //alert(data);

                if (data == 3) {
                    //location.reload( true );
                    //document.location.href = '<%=path%>campaignPublish.jsf';
                    //window.location.reload( true );
                    document.getElementById('id1').style.display = 'block';
                    setTimeout("testtimeout()",3000);

                }

                if (data == 1 || data == 0) {
                    //alert('in if'+videoid);
                    document.getElementById('id1').style.display = 'block';
                    setTimeout("testtimeout()",3000);

                }

                if (data == 2) {

                    //alert('success');
                    document.location.href = "campaignPublish.jsf?videoid="+videoid;
                    //window.location.reload( true );
                    return ;
                }

                xmlHttp = null;
            } else {
        //showMostViewedAdDiv();
        }
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }

    return false;
}


var timeout = 0;
function showGeneratedDynamicCouponImage()
{

    try{
        var xmlHttp = getHttpObject();

        var campaignId = document.getElementById('frmDynamicCouponPreview:hidCampaignId').value;
        var partnerlist = document.getElementById("partnerlist").value;
        var now = new Date();
        var url = "couponthumbnail.do?enduser_id=0&region_id=0&file_type=large&request_type=publish_coupon_preview&cmp_id="+campaignId;
        var url1 = "couponthumbnail.do?enduser_id=0&region_id=0&file_type=large&request_type=publish_coupon_preview&cmp_id="+campaignId;
        alert(partnerlist);
        if (null != partnerlist) {
            var partnerId = partnerlist.split(",");

            if (partnerId.length > 0) {
                //     alert("p0"+partnerId[0]+"gg");
                alert(partnerId[0]);
                url = url +"&partner_id="+partnerId[0]+"&time="+now.getTime();
            }
        }

        xmlHttp.onreadystatechange=function()
        {

            if(xmlHttp.readyState==4)
            {
                var length  = xmlHttp.getResponseHeader("image-length");
                // alert(length);
                if (null == length || length == 0) {
                    alert("faill");
                    setTimeout("showGeneratedDynamicCouponImage()",60000);
                }else {
                    alert("succcess");
                    if (partnerId.length > 0) {

                        
                        for (i = 0;i < partnerId.length;i++) {
                            
                            document.getElementById(partnerId[i]).src = url1 + "&partner_id="+partnerId[i]+"&time="+now.getTime();
                            alert(document.getElementById(partnerId[i]).src);
                        //   pause(1000);
                        }
                        document.getElementById(partnerId[0]).focus();
                        document.getElementById('frmDynamicCouponPreview:id2').style.display = 'block';
                        document.getElementById('frmDynamicCouponPreview:id1').style.display = 'none';
                    }
                }
                xmlHttp = null;
            // alert("failure"+length);
            }
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }catch(e){
        alert(e.message);
    }

    return false;
}
function pause(millis)

{
    var date = new Date();
    var curDate = null;



    do {
        curDate = new Date();
    }

    while(curDate-date < millis)

}

//Method from campaignPublish.jsp - End

//Method from unseenEditCount.jsp - Begin
function confirmDelete() {
    var unseen = document.getElementById('editunseen:UnseenCount').value;
    var message = 'You will block referral earnings of users who have missed more than ';
    message = message + unseen + ' ads. Are you Sure ?';
    if (unseen > 0) {
        if (!confirm(message)) {
            return false;
        }
    }
    return true;
}

//Method from unseenEditCount.jsp - End

//Method from cashOutPendingRequests.jsp - Begin
function checkOrUncheckUsersAllPending(chk) {
    var sltAllUsers = document.getElementById("frmCashOut:hdnSendToAll");

    for (var i = 0; i < document.frmCashOut.elements.length; i++) {
        var e = document.frmCashOut.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = chk.checked;
        //e.click();
        }

    } // end of for


    if (chk.checked) {
        sltAllUsers.value = true;
        document.getElementById("frmCashOut:hdnUncheckAll").value = false;
        document.getElementById("frmCashOut:dsltValues").value = "";

    } else {
        document.getElementById("frmCashOut:hdnUncheckAll").value = true;
        dsltIdList =  document.getElementById("frmCashOut:dsltValues").value = "";
        //document.getElementById("frmCashOut:alreadySelected").value = "";
        document.getElementById("frmCashOut:sltIdList").value = "";

        sltAllUsers.value = false;
    }

}

// Storing values when check all option is selected

function defaultSelectionsPending() {
    var selectedAll =  document.getElementById("frmCashOut:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("frmCashOut:dsltValues").value;
    //alert(selectedAll);

    if (eval(selectedAll) == true) {
        //alert("Inside true");
        checkUserPending();
    }else {
        unCheckUserPending();
    }

}

function checkUserPending() {

    for (var i = 0; i < document.frmCashOut.elements.length; i++) {
        var e = document.frmCashOut.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = true;
        }

    } // end of for

}

function unCheckUserPending() {

    for (var i = 0; i < document.frmCashOut.elements.length; i++) {
        var e = document.frmCashOut.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = false;
        }

    } // end of for

}

// Storing values already selected if navigated through different pages

function checkAllSelectedUsersPending() {
    var table = document.getElementById("frmCashOut:userList");
    // var selectedAll =  document.getElementById("frmCashOut:sltAllUser").value;
    var selectedAll =  document.getElementById("frmCashOut:hdnSendToAll").value;
    var sltIdList = document.getElementById("frmCashOut:sltIdList");
    var dsltIdList =  document.getElementById("frmCashOut:dsltValues").value;
    //alert(" Slt Id List in cashout :: " + sltIdList.value);

    if (table) {
        var rows = table.rows;
        //alert("Rows Length : " + rows.length );
        var i = 0;
        var sltIdArr = sltIdList.value.split(',');
        var dsltIdArr = dsltIdList.split(',');

        for (i = 1; i < rows.length; i++) {
            //alert(rows[i].innerHTML);
            var cells = rows[i].cells;

            var childrens = cells[0].childNodes;

            var hdnEndUserId = childrens[0].value;
            var chk = childrens[1];
            // alert(hdnEndUserId);

            if (eval(selectedAll) == true) {

                if (dsltIdArr.length > 0) {

                    var k = 0;
                    for(k = 0; k < dsltIdArr.length; k++) {

                        if (parseInt(hdnEndUserId) == parseInt(dsltIdArr[k])) {
                            // alert("inside the loop : " + dsltIdArr[k] + "  :: hidden Id :: " + hdnEndUserId);
                            // alert(" Chk : " + chk.type);
                            //alert("inside the == condition" + chk);
                            chk.checked = false;
                        }

                    } // end of for loop

                } //  end of if condition

            } else {

                if (sltIdArr.length > 0) {

                    //  alert("inside the loop : " + sltIdArr[0] + "  :: hidden Id :: " + hdnEndUserId);
                    var k = 0;
                    for(k = 0; k < sltIdArr.length; k++) {
                        //alert('Length ' + k + ' ' + sltIdArr[k] + ' ' + hdnEndUserId);
                        if (parseInt(hdnEndUserId) == parseInt(sltIdArr[k])) {
                            //alert("inside the == condition");
                            chk.checked = true;
                        }

                    } // end of for loop

                } //  end of if condition

            } // end of else condition

        //alert(hdnEndUserId);
        } // end of for loop

    } // end outer if condition

} // end of function

// Storing values when individual check boxes are checked in datatable

function storeSelectedCheckPending(chk, endUserId) {
    var sltIdList = document.getElementById("frmCashOut:sltIdList");
    var chkAll =  document.getElementById("frmCashOut:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("frmCashOut:dsltValues");

    if (chk && chk.checked) {

        sltIdList.value += endUserId + ",";
        if (eval(chkAll) == true) {
            var dsltArr = dsltIdList.value.split(",");
            var dsltVal = "";

            for (var j = 0; j < dsltArr.length - 1; j++) {

                if (parseInt(endUserId) != parseInt(dsltArr[j])) {
                    dsltVal += dsltArr[j] + ",";
                } // end of for loop

            } // end of for loop

            // remove from already selected list



            // give new value to the deselected values
            dsltIdList.value = dsltVal;
        } // end of if condition

    }else {


        var sltArr = sltIdList.value.split(",");
        var newValue = "";

        for (var i = 0; i < sltArr.length - 1; i++) {

            if (parseInt(endUserId) != parseInt(sltArr[i])) {
                newValue += sltArr[i] + ",";
            } // end of if condition

        } // end of for loop

        sltIdList.value = newValue;

        if (eval(chkAll) == true) {
            dsltIdList.value += endUserId + ",";
        } else {
    }


    } // end of else condition
}
//Method from cashOutPendingRequests.jsp - End


//Method from questionAdd.jsp- Begin
function checkDynSelectionQnAdd(obj) {
    try{
        if (obj.checked == 1) {
            return;
        } else {

            var id = obj.id;
            id = id.replace(/chk_UserType/, "options");

            var sltObj = document.getElementById(id);


            if(null != sltObj) {
                for(var i = 0; i < sltObj.options.length; i++) {
                    sltObj.options[i].selected = false;
                }
            }
        }

    }catch(e) {
        alert(e.message)
    }
}

//Method from questionAdd.jsp - End

//Method from pendingDisbursement.jsp - Begin

function checkOrUncheckUsersAllDisb(chk) {
    var sltAllUsers = document.getElementById("frmCashOut:hdnSendToAll");

    for (var i = 0; i < document.frmCashOut.elements.length; i++) {
        var e = document.frmCashOut.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = chk.checked;
        //e.click();
        }

    } // end of for


    if (chk.checked) {
        sltAllUsers.value = true;
        document.getElementById("frmCashOut:hdnUncheckAll").value = false;
        document.getElementById("frmCashOut:dsltValues").value = "";

    }else {
        document.getElementById("frmCashOut:hdnUncheckAll").value = true;
        dsltIdList =  document.getElementById("frmCashOut:dsltValues").value = "";
        //document.getElementById("frmCashOut:alreadySelected").value = "";
        document.getElementById("frmCashOut:sltIdList").value = "";

        sltAllUsers.value = false;
    }

}

// Storing values when check all option is selected

function defaultSelectionsDisb() {
    var selectedAll =  document.getElementById("frmCashOut:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("frmCashOut:dsltValues").value;
    //alert(selectedAll);

    if (eval(selectedAll) == true) {
        //alert("Inside true");
        checkUserDisb();
    } else {
        unCheckUserDisb();
    }

}

function checkUserDisb() {

    for (var i = 0; i < document.frmCashOut.elements.length; i++) {
        var e = document.frmCashOut.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = true;
        }

    } // end of for

}

function unCheckUserDisb() {

    for (var i = 0; i < document.frmCashOut.elements.length; i++) {
        var e = document.frmCashOut.elements[i];

        if (e.type == 'checkbox' && !e.disabled) {
            e.checked = false;
        }

    } // end of for

}

// Storing values already selected if navigated through different pages

function checkAllSelectedUsersDisb() {
    var table = document.getElementById("frmCashOut:userList");
    // var selectedAll =  document.getElementById("frmCashOut:sltAllUser").value;
    var selectedAll =  document.getElementById("frmCashOut:hdnSendToAll").value;
    var sltIdList = document.getElementById("frmCashOut:sltIdList");
    var dsltIdList =  document.getElementById("frmCashOut:dsltValues").value;
    //alert(" Slt Id List in cashout :: " + sltIdList.value);

    if (table) {
        var rows = table.rows;
        //alert("Rows Length : " + rows.length );
        var i = 0;
        var sltIdArr = sltIdList.value.split(',');
        var dsltIdArr = dsltIdList.split(',');

        for (i = 1; i < rows.length; i++) {
            //alert(rows[i].innerHTML);
            var cells = rows[i].cells;

            var childrens = cells[0].childNodes;

            var hdnEndUserId = childrens[0].value;
            var chk = childrens[1];
            // alert(hdnEndUserId);

            if (eval(selectedAll) == true) {

                if (dsltIdArr.length > 0) {

                    var k = 0;
                    for(k = 0; k < dsltIdArr.length; k++) {

                        if (parseInt(hdnEndUserId) == parseInt(dsltIdArr[k])) {
                            // alert("inside the loop : " + dsltIdArr[k] + "  :: hidden Id :: " + hdnEndUserId);
                            // alert(" Chk : " + chk.type);
                            //alert("inside the == condition" + chk);
                            chk.checked = false;
                        }

                    } // end of for loop

                } //  end of if condition

            }else {

                if (sltIdArr.length > 0) {

                    //  alert("inside the loop : " + sltIdArr[0] + "  :: hidden Id :: " + hdnEndUserId);
                    var k = 0;
                    for(k = 0; k < sltIdArr.length; k++) {
                        //alert('Length ' + k + ' ' + sltIdArr[k] + ' ' + hdnEndUserId);
                        if (parseInt(hdnEndUserId) == parseInt(sltIdArr[k])) {
                            //alert("inside the == condition");
                            chk.checked = true;
                        }

                    } // end of for loop

                } //  end of if condition

            } // end of else condition

        //alert(hdnEndUserId);
        } // end of for loop

    } // end outer if condition

} // end of function

// Storing values when individual check boxes are checked in datatable

function storeSelectedCheckDisb(chk, endUserId) {
    var sltIdList = document.getElementById("frmCashOut:sltIdList");
    var chkAll =  document.getElementById("frmCashOut:hdnSendToAll").value;
    var dsltIdList =  document.getElementById("frmCashOut:dsltValues");

    if (chk && chk.checked) {

        sltIdList.value += endUserId + ",";
        if (eval(chkAll) == true) {
            var dsltArr = dsltIdList.value.split(",");
            var dsltVal = "";

            for (var j = 0; j < dsltArr.length - 1; j++) {

                if (parseInt(endUserId) != parseInt(dsltArr[j])) {
                    dsltVal += dsltArr[j] + ",";
                } // end of for loop

            } // end of for loop

            // remove from already selected list



            // give new value to the deselected values
            dsltIdList.value = dsltVal;
        } // end of if condition

    } else {


        var sltArr = sltIdList.value.split(",");
        var newValue = "";

        for (var i = 0; i < sltArr.length - 1; i++) {

            if (parseInt(endUserId) != parseInt(sltArr[i])) {
                newValue += sltArr[i] + ",";
            } // end of if condition

        } // end of for loop

        sltIdList.value = newValue;

        if (eval(chkAll) == true) {
            dsltIdList.value += endUserId + ",";
        }else {
    }


    } // end of else condition

}

//Method from pendingDisbursement.jsp - End

//Method from endUserForgotPassword.jsp - Begin
function CatchKey(evt)
{

    var obj = document.getElementById("loginform:Email");
    obj.focus();
    evt = (evt) ? evt : ((window.event) ? event : null);
    //alert(evt);
    if (evt)
    {
        var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        //alert("id: " + elem.id);
        if (elem)
        {
            var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
            //alert(charCode);
            if ( charCode == 13 )
            {
                //fun();
                //if (obj.value.length > 0) {
                document.getElementById('loginform:submitBtnId').focus();
            // document.getElementById('loginform:submitBtnId').click();
            //}
            }

        }
    }
}

//Method from endUserForgotPassword - End

//Method from editCampaignDetails.jsp - Begin

function validateCouponExpiryDateEditCampaign() {
    var adEndDate =document.getElementById('editCampaignDetails:hdnAdEndDate').value;

    var couponTypes = document.editCampaignDetails["editCampaignDetails:rdoCoupon"];
    var origCouponTypeId = document.getElementById("hiddenTypeId").value;
    
    if (null != couponTypes && !couponTypes[0].checked && origCouponTypeId != 0) {
        if (null != document.getElementById('editCampaignDetails:CouponExpiryDate'+'.day')){
            document.getElementById('editCampaignDetails:CouponExpiryDate'+'.day').value = '';
        }
        if (null != document.getElementById('editCampaignDetails:CouponExpiryDate'+'.month')){
            document.getElementById('editCampaignDetails:CouponExpiryDate'+'.month').value = '-1';
        }
        if (null != document.getElementById('editCampaignDetails:CouponExpiryDate'+'.year')) {
            document.getElementById('editCampaignDetails:CouponExpiryDate'+'.year').value = '';
        }
    }

    if (null != couponTypes && null != origCouponTypeId && !couponTypes[1].checked && origCouponTypeId != 1) {

        if (null != document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.day')) {
            document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.day').value = '';
        }
        if (null != document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.month')) {
            document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.month').value = '-1';
        }
        if (null != document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.year')) {
            document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.year').value = '';
        }
    }

    var mySplitResult = adEndDate.split("-");
    var adDay = mySplitResult[1];
    var adMonth = mySplitResult[0];
    var adYear = mySplitResult[2];
    var couponDay, couponMonth, couponYear;

    adEndDate = new Date(adYear,adMonth,adDay);
    
    if (couponTypes[0].checked) {
        couponDay = document.getElementById('editCampaignDetails:CouponExpiryDate'+'.day').value;
        couponMonth = document.getElementById('editCampaignDetails:CouponExpiryDate'+'.month').value;
        couponYear = document.getElementById('editCampaignDetails:CouponExpiryDate'+'.year').value;
    } else {
        couponDay = document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.day').value;
        couponMonth = document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.month').value;
        couponYear = document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.year').value;
    }
    var couponExpiryDate = new Date(couponYear,couponMonth,couponDay);

    if (couponExpiryDate < adEndDate) {
        if(!(confirm('The coupon expiry date is before the ad end date. Are you sure to proceed with this?'))) return false;
    } else {
        return true;
    }
}
//Method from editCampaignDetails.jsp - End

//Method from approvedCampaignDetails.jsp - Begin
function showPayoutBudgetField(radio) {

    if (radio.value == 1) {
        document.getElementById('cmpDetails:payoutBudget').style.display = 'block';
        document.getElementById('cmpDetails:budgetTextId').style.display = 'block';
        document.getElementById('cmpDetails:calculateId').style.display = 'block';
    }
    else {
        document.getElementById('cmpDetails:payoutBudget').style.display = 'none';
        document.getElementById('cmpDetails:budgetTextId').style.display = 'none';
        document.getElementById('cmpDetails:calculateId').style.display = 'none';
    }

}

function hidePayoutBudgetField() {

    document.getElementById('cmpDetails:payoutBudget').style.display = 'none';
    document.getElementById('cmpDetails:budgetTextId').style.display = 'none';

}

function clearValues()
{
    //alert(document.getElementById('cmpDetails:desiredNoofUsers'));

    if (null != document.getElementById('cmpDetails:payoutBudget'))
    {
        document.getElementById('cmpDetails:payoutBudget').value = 0.0;
    }

    if (null != document.getElementById('cmpDetails:desiredNoofUsers'))
    {
        document.getElementById('cmpDetails:desiredNoofUsers').value = 0;
    }

    if (null != document.getElementById('cmpDetails:earningsPerView'))
    {
        document.getElementById('cmpDetails:earningsPerView').value = 0.35;
    }

    if (null != document.getElementById('cmpDetails:ProfitPerView'))
    {
        document.getElementById('cmpDetails:ProfitPerView').value = 0.50;
    }
    this.focus();
}

//Method from approvedCampaignDetails - End

//Method from publishCampaign.jsp - Begin
function showReason()
{

    document.getElementById("reasonText").style.visibility="visible";
    document.getElementById("reasonText").style.display="block";
    document.getElementById("publishForm:publish").style.visibility="hidden";
    document.getElementById("publishForm:reject").style.visibility="hidden";
    document.getElementById("publishForm:back").style.visibility="hidden";
    document.getElementById("publishForm:submit").style.visibility="visible";
    document.getElementById("publishForm:cancel").style.visibility="visible";

    //document.getElementById("approveButton").style.visibility="hidden";
    //document.getElementById("submitButton").style.display="none";
    return false;

}
//Method from publishCampaign.jsp - End

//Method from advertiserReport.jsp - Begin
function printDiv()
{
    document.getElementById('divToHide').style.visibility = 'hidden';
    var divToPrint=document.getElementById("divToPrint");
    newWin= window.open("");
    newWin.document.write('<link rel="stylesheet" type="text/css" href="style/eazy.css" media="print,screen" />');
    newWin.document.write(divToPrint.innerHTML);
    document.getElementById('divToHide').style.visibility = 'visible';
    newWin.document.close();
    newWin.print();
    newWin.close();

}
/**
     * Shreeja Ravindranathan
     * 15.03.10
     * function used to hide/display coupon details
     * based on whether static or dynamic coupon is selected
     **/
function hideCouponDetailsBasedOnCouponType(couponType) {

    if (couponType == -1) {

        if (null != document.forms['editCampaignDetails']['editCampaignDetails:rdoCoupon'] &&
            document.forms['editCampaignDetails']['editCampaignDetails:rdoCoupon'][0].checked) {
            couponType = 0;
        } else {
            couponType = 1;
        }
    }


    if (couponType == 1) { //if dynamic,show the dynamic coupon div & hide static coupon div
        if (null != document.getElementById("staticCoupon")) {
            document.getElementById("staticCoupon").style.display="none";
        }
        if (null != document.getElementById("dynamicCoupon")) {
            document.getElementById("dynamicCoupon").style.display="";
        }
        /*if (null != document.getElementById("editCampaignDetails:CouponUrl")) {
            document.getElementById("editCampaignDetails:CouponUrl").value="http://";
        } else {
            if (null != document.getElementById("frmCreateAd:CouponUrl")) {
                document.getElementById("frmCreateAd:CouponUrl").value="http://";
            }
        }*/

        if (null != document.getElementById("frmCreateAd:previewBtn")) {
            document.getElementById("frmCreateAd:previewBtn").style.display="";
        } else if (null != document.getElementById("editCampaignDetails:previewBtn")) {
            document.getElementById("editCampaignDetails:previewBtn").style.display="";
        }
    } else {
        if (null != document.getElementById("staticCoupon")) {
            document.getElementById("staticCoupon").style.display="";
        }
        if (null != document.getElementById("dynamicCoupon")) {
            document.getElementById("dynamicCoupon").style.display="none";
        }
        if (null != document.getElementById("frmCreateAd:previewBtn")) {
            document.getElementById("frmCreateAd:previewBtn").style.display="none";
        } else if (null != document.getElementById("editCampaignDetails:previewBtn")) {
            document.getElementById("editCampaignDetails:previewBtn").style.display="none";
        }
    }
}



function autoLogin()
{
    var autoLogin = document.getElementById("hdnAutoLogin").value;

    if (true == autoLogin || "true" == autoLogin) {
        var userName = document.getElementById("hdnUserName").value;
        var password = document.getElementById("hdnPassword").value;
        var userTypeId = document.getElementById("hdnUserTypeId").value;
        alert("type id ="+userTypeId);
        try{
            var xmlHttp = getHttpObject();
            alert(xmlHttp)
            var url = "endUserAutoLoginAjax.jsp?userName="+userName+"&password="+password+"&userTypeId="+userTypeId;
            alert(url);
            xmlHttp.onreadystatechange=function()
            {
                alert(xmlHttp.readyState);
                if(xmlHttp.readyState==4)
                {
                    alert("inside");
                    setTimeout("alert('5 seconds over')",5000);
                    
                //  xmlHttp = null;
                } else {
            //showMostViewedAdDiv();
            }
            }
            xmlHttp.open("GET",url,true);
            xmlHttp.send(null);
        }catch(e){
            alert(e.message);
        }
    }
    return false;
}

function showMessage(id, message) {
    var obj=$(id)[0];
    var tip = null;
    if (!tip) {
        tip = $('<div id="' + id.replace('#', '') + '_message" class="tipsy"><div class="tipsy-inner">' + message + '</div></div>');
        tip.css({
            position: 'absolute',
            zIndex: 100000
        });
    //$.data(obj, 'active.tipsy', tip);
    }

    var pos = $.extend({}, $(obj).offset(), {
        width: obj.offsetWidth,
        height: obj.offsetHeight
    });
    tip.remove().css({
        top: 0,
        left: 0,
        visibility: 'visible',
        display: 'block'
    }).appendTo(document.body);
    var actualWidth = tip[0].offsetWidth, actualHeight = tip[0].offsetHeight;
    if (id != "#txtFirstName") {
        tip.css({
            top: pos.top + pos.height / 2 - actualHeight / 2,
            left: pos.left + pos.width
        }).addClass('tipsy-west');
    } else {
        tip.css({
            top: pos.top - (actualHeight+30) / 2,
            left: pos.left + (pos.width-90)
        }).addClass('tipsy-south');
    }
}

function hideMessage(id) {
    $(id+"_message").hide();
}

function DisableButton(b)
{
    //alert(b.value);
    //b.disabled = true;
    document.getElementById('questionarefrm:submitId').style.display = 'none';
    document.getElementById('questionarefrm:submitId1').style.display = 'block';
    return true;

}

function DisableButton1(b)
{
    // alert('NEW BUTTON');
    return false;

}

function validateCashOut(elem) {

    var totPoints = document.getElementById('balancePoint').value;
    var regPoints = document.getElementById('regPoint').value;

    var objPaypalAmount = document.getElementById("frmBeezagCares:paypalAmount");
    var paypalAmount = 0;

    //alert(objPaypalAmount.value + " " + totPoints);

    if (null != objPaypalAmount) {
        // alert("pa" + objPaypalAmount.value);
        paypalAmount = parseInt(objPaypalAmount.value);
    }

    if (paypalAmount > totPoints) {
        //addMessage("Points exceeds available points in your account");
        document.getElementById('mesgDiv').innerHTML = "Points exceeds available points in your account";

        if (document.getElementById("frmBeezagCares:errorMsgId") != null ) {
            document.getElementById("frmBeezagCares:errorMsgId").innerHTML='';
        }

        if (elem) {
            elem.value = "";
            document.getElementById("paymentAmountId").value = "";
        }
        couponPopup(1);
        window.scrollTo(0, 0);
    } else {

        if (paypalAmount % regPoints == 0) {
            //alert(document.getElementById("paymentAmountId"));
            document.getElementById("paymentAmountId").innerHTML = (objPaypalAmount.value / regPoints).toFixed(2);
        } else {
            document.getElementById("paymentAmountId").value = "0.00";
        }
    //addMessage("");
    //clearErrMsgDiv();
    }

}

function checkAmount() {

    var totPoints = document.getElementById('balancePoint').value;
    var regPoints = document.getElementById('regPoint').value;

    var objPaypalAmount = document.getElementById("frmBeezagCares:paypalAmount");
    var paypalAmount = 0;   

    if (null != objPaypalAmount) {        
        paypalAmount = parseInt(objPaypalAmount.value);
    }

    if (objPaypalAmount.value != '') {
        //alert(totPoints + ' ' +paypalAmount % regPoints);

        if (paypalAmount > totPoints) {
            document.getElementById('mesgDiv').innerHTML =
            "Points exceeds available points in your account";

            if (document.getElementById("frmBeezagCares:errorMsgId") != null ) {
                document.getElementById("frmBeezagCares:errorMsgId").innerHTML='';
            }

            couponPopup(1);
            return false;
        }

        if (paypalAmount % regPoints != 0 || paypalAmount == 0) {            

            document.getElementById('mesgDiv').innerHTML =
            "Please enter a multiple of " + regPoints + " for the number of points to redeem.";

            if (document.getElementById("frmBeezagCares:errorMsgId") != null ) {
                document.getElementById("frmBeezagCares:errorMsgId").innerHTML='';
            }
            couponPopup(1);
            return false;
        }
    } else {
        document.getElementById('mesgDiv').innerHTML = "Enter points to redeem.";
        couponPopup(1);
        return false;
    }

    return true;

}

function isNumeric(elem){
    var numericExpression = '/[0-9]+$/';
    alert(elem);
    if(elem.match(numericExpression)){
        return true;
    }else{
        alert('failed');
        elem.focus();
        return false;
    }
}


function restoreValues(points) {    
    var radioObj = document.forms['frmBeezagCares']['frmBeezagCares:paymentType'];
    var pointObj = document.forms['frmBeezagCares']['frmBeezagCares:paypalAmount'];
    var balanceObj = document.getElementById('paymentAmountId');
    balanceObj.innerHTML = (pointObj.value / points).toFixed(2);

    for (var i=0; i < radioObj.length; i++) {

        if (radioObj[i].checked) {
            var rad_val = radioObj[i].value;
            if (rad_val == 3) {
                document.getElementById("frmBeezagCares:charityDiv").style.display = 'block';
            } else {
                document.getElementById("frmBeezagCares:charityDiv").style.display = 'none';
            }

        }
    }
}

function setValue(amount, mode, charity, points) {

    if (amount != 0 ) {
        var radioObj = document.forms['frmBeezagCares']['frmBeezagCares:paymentType'];
        var charityObj = document.forms['frmBeezagCares']['frmBeezagCares:charityType'];

        if (amount > 0) {
            document.getElementById('frmBeezagCares:paypalAmount').value = amount * points;
        }
        var balanceObj = document.getElementById('paymentAmountId');
        balanceObj.innerHTML = (amount).toFixed(2);

        if (mode == 3) {
            document.getElementById("frmBeezagCares:charityDiv").style.display = 'block';
        } else {
            document.getElementById("frmBeezagCares:charityDiv").style.display = 'none';
        }

        for (var i=0; i < radioObj.length; i++) {

            if (radioObj[i].value == mode) {
                radioObj[i].checked = true;

            }
        }

        for (var i=0; i < charityObj.length; i++) {

            if (charityObj[i].value == charity) {
                charityObj[i].checked = true;

            }
        }
    }
    
}

function hideSubmitButton() {
    document.getElementById('questionarefrm:submitId').style.display = 'none';
    document.getElementById('questionarefrm:submitId1').style.display = 'block';
        
}

/**
     * gets account balance & coupon offer counts from database
     */
function getEndUserCountersFromDB() {
        
    $.ajax({
        url: "enduserCountersAjax.jsp",
        cache: false,
        contentType: "text",
        method: "get",
        success: function(data)
        {
            var arr = new Array();
            arr = data.split("|");

            if(arr.length == 3) {
                $("#pnlPoints").text(arr[0]);
                $("#pnlTotalOffers").text(arr[1]);
                $("#pnlOffersExpiredSoon").text(arr[2]);
            }
        }
    });
}


/*function testtimeout() {
    $.ajax({
        url:"checkStatusAjax.jsp",
        cache:false,
        contentType: "text",
        method: "get",
        success: function(data)
        {
            var arr = new Array();
            arr = data.split("|");
            $("#testId").text(arr[0]);
        }
        
    });
}*/

function checkSPPV() {

    var epv = document.getElementById("cmpDetails:earningsPerView").value;
    var sppv = document.getElementById("cmpDetails:ProfitPerView").value;

    if (eval(epv) > eval(sppv)) {
            
        if (confirm("Suggested Pay per View is less than Earnings per View.This would result in a loss.Do you want to continue?")) {
            return true;
        } else {
            return false;
        }
    }

    return true;
}

function resendEmail()
{
    var fireOnThis = document.getElementById("resendId");
    if (document.createEvent)
    {
        var evObj = document.createEvent('MouseEvents')
        evObj.initEvent( 'click', true, false )
        fireOnThis.dispatchEvent(evObj)
    }
    else if (document.createEventObject)
    {
        fireOnThis.fireEvent('onclick')
    }
}

function checkSpecialCouponExpiryDate() {

    var couponTypes = document.editCampaignDetails["editCampaignDetails:rdoCoupon"];
    var origCouponTypeId = document.getElementById("hiddenTypeId").value;

    if (!couponTypes[0].checked && origCouponTypeId != 0) {
        document.getElementById('editCampaignDetails:CouponExpiryDate'+'.day').value = '';
        document.getElementById('editCampaignDetails:CouponExpiryDate'+'.month').value = '-1';
        document.getElementById('editCampaignDetails:CouponExpiryDate'+'.year').value = '';
    }

    if (!couponTypes[1].checked && origCouponTypeId != 1) {

        document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.day').value = '';
        document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.month').value = '-1';
        document.getElementById('editCampaignDetails:dynamicCouponCouponExpiryDate'+'.year').value = '';
    }

    return true;
  }



function checkDateFields() {

    if (!validateAllQnDateFields()) {
        return false;
    }

    return true;
}

/**
 * validates all dates fields in question creation page
 */
function validateAllQnDateFields() {

    if (!validateQnDateIfFilled("optionList:startDateId")
        | !validateQnDateIfFilled("optionList:expiryDateId")) {
        return false;
    }
    return true;
}

/**
 * validates dateElement If filled
 */
function validateQnDateIfFilled(dateElement) {

    if ((null == document.getElementById(dateElement))
        || (null == document.getElementById(dateElement + ".day"))
        || (null == document.getElementById(dateElement + ".month"))
        || (null == document.getElementById(dateElement + ".year"))) {
        return true;
    }
    var dayfield = document.getElementById(dateElement + ".day").value;
    var monthfield = document.getElementById(dateElement + ".month").value;
    var yearfield = document.getElementById(dateElement + ".year").value;
    var validDate = true;


    if (null != document.getElementById("optionList:QnexpiryDateId")) {
        document.getElementById("optionList:QnexpiryDateId").innerHTML = ''
    }

    if (null != document.getElementById("optionList:QnstartDateId")) {
        document.getElementById("optionList:QnstartDateId").innerHTML = ''
    }

    // removes previous error message if exists
    if (null != document.getElementById(dateElement + ".errorMesg")) {
        document.getElementById(dateElement).removeChild(
            document.getElementById(dateElement + ".errorMesg"));
    }

    if((dayfield == '') && (monthfield == -1) && (yearfield== '')) {
        validDate = true;
    }else if ((dayfield == '') || (monthfield == -1) || (yearfield== '')) {
        validDate = false;
    } else {
        var dayobj = new Date(yearfield, monthfield-1, dayfield);
        if ((dayobj.getMonth()+1 != monthfield)||(dayobj.getDate()!= dayfield)
            ||(dayobj.getFullYear()!= yearfield)) {
            validDate = false;
        }
    }

    // adds errormesg if date not valid
    if(!validDate) {
        var errorMesg = document.createElement("span");
        errorMesg.id = dateElement + ".errorMesg";
        errorMesg.innerHTML = "The given value is not a correct date.";
        errorMesg.className = "errordynamic";
        document.getElementById(dateElement).appendChild(errorMesg);
        document.getElementById(dateElement + ".day").focus();
    }
    return validDate;
}


    function popupAdCount(obj, url)
    {
        var now = new Date();

        url += "&time=" + now.getTime();
        try{
            var xmlHttp = getHttpObject();

            xmlHttp.onreadystatechange=function()
            {

                if(xmlHttp.readyState==4)
                {
                    var data = xmlHttp.responseText;
                    var arr = new Array();
                    arr = data.split("|");
                    
                    document.getElementById("popuup_div").style.width = '110px';
                    var popupDiv =  document.getElementById("popuup_div");
                    var placement = findPos(obj);
                    popupDiv.style.left = placement[0] + "px";
                    popupDiv.style.top = placement[1] + "px";
                    popupDiv.style.display = 'block';
                    if(arr.length == 2) {
                        document.getElementById("adViewCount").innerHTML = arr[0].trim();
                        document.getElementById("pendingCount").innerHTML = arr[1];
                    }
    
                    xmlHttp = null;
                }

            }
            xmlHttp.open("GET",url,true);
            xmlHttp.send(null);
        }catch(e){
            alert(e.message);
        }

        return false;
    }


